Bastien
Bastien

Reputation: 3087

Adding a categorical color to plot_ly markers invert the size of the points displayed

I'm trying to make a plot with plotly that have colors representing some class (factor ff in my example) and the size representing the population size (column ss in my example). Plotting with a constant color makes the graph ok, i.e. the size of the dots are representative. However, if I add the color=~ff argument to the call, the sizes displayed change and seems inverted!

Here is a RE:

# preparing the session and data:
library(plotly)
dd <- data.frame(
  xx = rnorm(10),
  yy = rnorm(10),
  ff = as.factor(c("a","b","c","a","b","c","a","a","b","c")),
  ss = round(runif(10, 100,1000))
)

The first plot with no color argument:

pp1 <- plot_ly(data = dd,
              x = ~xx,
              y = ~yy,
              marker = list(sizeref = mean(dd$ss)/25,
                            size= ~ss ,
                            sizemode= "diameter",
                            mode = "markers")
              ) 
add_markers(pp1,mode = "markers")

Note: the way I set sizeref may look weird but it's the only way I found to make my size pretty in my real code were population size varies greatly. I dough that this causes my problem but it may so I decide to keep it in my example

This gives: enter image description here

Now when I add the color argument:

pp2 <- plot_ly(data = dd,
              x = ~xx,
              y = ~yy,
              color = ~ff,  ####  !!!  The only line difference
              marker = list(sizeref = mean(dd$ss)/25,
                            size= ~ss ,
                            sizemode= "diameter",
                            mode = "markers")
) 
add_markers(pp2,mode = "markers")

gives:

enter image description here

The colors are ok but the sizes changed and seems inverted.

Any idea what I did wrong? Could it be that the sizeref argument is then applied by category ff? If yes, how to deal with it?

Upvotes: 1

Views: 369

Answers (1)

MLavoie
MLavoie

Reputation: 9836

I am not sure how you set your sizeref, but have you tried this:

plot_ly(data = dd, x = ~xx, y = ~yy, color = ~ff, size= ~ss) %>% 
add_markers(marker = list(sizeref = 3, sizemode= "diameter"))

Upvotes: 1

Related Questions