首页 > 解决方案 > 在 R 中转换为 plotly 时散点图颜色丢失

问题描述

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

    # 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 图中指示的“填充”颜色?

标签: rggplot2graphplotlyvisualization

解决方案


经过一些故障排除后,您似乎可以调用shape = 21in 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


推荐阅读