简体   繁体   English

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

[英]Scatterplot colors lost when converting to plotly in R

I'm trying to build a bubbleplot with, for example, the following data: 我正在尝试使用以下数据构建气泡图:

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

When I run a ggplot command to create a colored scatterplot, I get more or less what I want (code and figure below): 当我运行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 气泡图的图像,按计数变量着色

However, when I use the following command to convert this plot to an interactive plotly graph, I lose the color distinction (see figure below). 但是,当我使用以下命令将此图转换为交互式图时,会失去颜色区别(请参见下图)。 I've scratched my head over this for a while now, and can't seem to find a solution to the problem...Plotly seems to retain color distinction for other types of graphs I've made (eg bar charts). 我已经为此花了一段时间,似乎无法找到解决问题的方法……对于我制作的其他类型的图形(例如条形图),Plotly似乎保留了颜色区分。

I also get the attached warning message: 我还收到附件警告消息:

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 相同图形的绘图版本

Does anyone have an idea of what is going on / how to retain the "fill" coloring I indicated in the original ggplot graph? 有谁知道发生了什么/如何保留我在原始ggplot图中指示的“填充”颜色?

After some troubleshooting, it seems to be your call to shape = 21 in geom_point . 经过一些故障排除后,似乎是您在geom_point调用shape = 21 Try this workaround instead: 请尝试以下解决方法:

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)

Note: you'll have to change all your fill calls to color (including scale_color_viridis ) 注意:您必须将所有fill调用更改为color (包括scale_color_viridis

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

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