繁体   English   中英

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

[英]Scatterplot colors lost when converting to plotly in 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()

气泡图的图像,按计数变量着色

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

我还收到附件警告消息:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM