Sasha Sasha - 1 month ago 22
R Question

How to reproduce this ggplot graph in plotly?

I would like to reproduce this ggplot graph by using native plotly functionality

ggplot(mtcars, aes(x="mpg", y=mpg))+
geom_boxplot()+geom_jitter(aes(color = mpg),width = 0.3,size=4)+
scale_color_gradient(low="blue", high="yellow", guide = 'none')
ggplotly()


I am trying to do something like this

plot_ly(data=mtcars, y = ~mpg,
type = "box", boxpoints = "all", jitter = 0.3,
marker=list(color=~mpg, size=10),pointpos = 0)


But I can't find the way to control the color of the points (color=~mpg does not do anything)

The reason that I need it to be implemented using native plotly rather then with the "plotlyfied" ggplot as mentioned above is that I need style consistency with other plots that were implemented in native plotly.

dww dww
Answer

This is a little bit of a hack, but it works:

  1. use a separate trace to draw the boxplot (without points)
  2. add a 2nd trace of type scatter to draw the points
  3. unfortunately, scatter traces don't accept jitter as an argument
  4. this means we need to use a continuous scale on the x-axis and add jitter using rnorm
  5. we don't really want the x axis to look like a continuous numeric scale, so we set the tick labels manually to look like categories

Like this:

plot_ly(data=mtcars) %>%
  add_trace(y = ~mpg, x=1, type = "box", boxpoints = "none") %>%
  add_trace(type="scatter", mode="markers", 
            y=~mpg, x=rnorm(nrow(mtcars),1,0.05), marker=list(color = ~mpg, size=10))%>%
  layout(xaxis = list(tickmode="array", tickvals=c(1), ticktext=c("mtcars") )) 

enter image description here

You can extend this approach to have more than one category like this

plot_ly(data=mtcars) %>%
  add_trace(y = ~mpg, x=~gear, type = "box", boxpoints = "none") %>%
  add_trace(type="scatter", mode="markers", y=~mpg, 
            x = ~gear+rnorm(nrow(mtcars),0,0.1), 
            marker=list(color = ~mpg, size=10))%>%
  layout(xaxis = list(tickmode="array", tickvals=c(3,4,5), ticktext=c("3","4","5") )) 

enter image description here

To control the marker colors, you can use the colorscale argument, together with autocolorscale = FALSE

The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required.

For example,

cs = list(list(0, rgb(0,0,1)), list(1, rgb(1,1,0)))
plot_ly(data=mtcars) %>%
  add_trace(y = ~mpg, x=1, type = "box", boxpoints = "none") %>%
  add_trace(type="scatter", mode="markers", 
            y=~mpg, x=rnorm(nrow(mtcars),1,0.05), 
            marker=list(color = ~mpg, autocolorscale=F, 
                        colorscale = cs, size = 10)) %>%
  layout(xaxis = list(tickmode="array", tickvals=c(1), ticktext=c("mtcars") )) 

enter image description here

Comments