在R中转换为散点图时散点图颜色丢失

时间:2019-03-01 17:10:19

标签: r ggplot2 graph plotly visualization

我正在尝试使用以下数据构建气泡图:

    # 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()

Image of bubble plot, colored by count variable

但是,当我使用以下命令将此图转换为交互式图时,我失去了颜色区分(请参见下图)。我已经为此花了一段时间,似乎无法找到解决问题的方法……对于我制作的其他类型的图形(例如条形图),Plotly似乎保留了颜色区分。 / 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

Plotly version of the same graph

是否有人知道发生了什么/如何保留我在原始ggplot图中指示的“填充”颜色?

1 个答案:

答案 0 :(得分:0)

经过一些故障排除后,似乎是您在shape = 21中致电geom_point。请尝试以下解决方法:

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