当在R中转换为绘图时,散点图颜色丢失了



我正在尝试使用例如以下数据来构建一个泡泡图:

    # install.packages("tidyverse")
    # install.packages("plotly")
    # install.packages("viridis")
    library(tidyverse)
    library(plotly) 
    library(viridis) 
    data <- tribble(
    ~race, ~gender, ~count, 
    "race1", "gender1", 15, 
    "race1", "gender2", 58,
    "race1", "gender3", 59,
    "race2", "gender1", 100,
    "race2", "gender2", 12,
    "race2", "gender3", 13, 
    "race3", "gender1", 14, 
    "race3", "gender2", 39, 
    "race3", "gender3", 87
    )

当我运行一个ggplot命令来创建彩色散点图时,我或多或少会得到我想要的(代码和图):

bubble <- ggplot(data = data, aes(x = race, y = gender)) + 
  geom_point(aes(size = log10(count) * 4, fill = count), shape = 21) + 
  scale_fill_viridis(discrete = F) +
  geom_text(aes(label = count), size = 4) +
  scale_size_identity() +
  xlab("Race") + 
  ylab("Gender") + 
  theme_classic()

气泡图的图像,通过计数变量颜色

但是,当我使用以下命令将此图转换为交互式绘图图时,我会失去颜色区别(请参见下图)。我已经挠头了一段时间,似乎找不到解决问题的解决方案。。。。。。。。。。。。。。。。。。。。。。。。。/p>

我还收到附带的警告消息:

ggplotly(bubble)
> Warning message:
In L$marker$color[idx] <- aes2plotly(data, params, "fill")[idx] :
  number of items to replace is not a multiple of replacement length

同一图的绘图版本

有人知道正在发生的事情/如何保留我在原始GGPLOT图中指示的"填充"着色?

进行一些故障排除后,似乎是您在geom_point中对shape = 21的呼吁。尝试使用此解决方法:

bubble <- ggplot(data = data, aes(x = race, y = gender)) + 
  geom_point(aes(size = log10(count) * 4, color = count)) + 
  scale_color_viridis(discrete = F) +
  geom_text(aes(label = count), size = 4) +
  scale_size_identity() +
  xlab("Race") + 
  ylab("Gender") + 
  theme_classic()
ggplotly(bubble)

注意:您必须将所有fill调用更改为color(包括scale_color_viridis