简体   繁体   中英

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

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

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?

After some troubleshooting, it seems to be your call to shape = 21 in geom_point . 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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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