5
votes

I'm trying to superimpose a scatter on top of a grouped bar chart in plotly. However, whereas in a simple bar chart the scatter points are correctly placed at the top of the respective bars, in a grouped bar chart the scatter points do not automatically adjust.

Here is an example demonstrating the problem:

set.seed(1)
d1 <- data.frame(x=rep(c('a', 'b', 'c'), each=2),
                 y=rnorm(6, mean=10),
                 c=rep(c('q', 'r'), times=3))
d2 <- d1[d1$c=='q', ]

p1 <- plot_ly(data=d2, x=~x, y=~y, type='bar')
p2 <- add_trace(p1, data=d2, x=~x, y=~y, 
                type='scatter', mode='markers', marker=list(size=20))
p3 <- plot_ly(data=d1, x=~x, y=~y, color=~c, type='bar')
p4 <- add_trace(p3, data=d1, x=~x, y=~y, 
                type='scatter', mode='markers', marker=list(size=20))

subplot(p1, p2, p3, p4, nrows=2)

This generates the following figure: enter image description here

Whereas in the top right panel (p2) the points are placed at their respective bars, in the bottom right (p4), the points do not adjust to the colour factor.

I can imagine solving this problem by setting x as a numeric variable and manually, adjusting the points by a small amount, etc. But this seems rather tedious. Is there a simple way to make plotly do the adjustment?

(Obviously the goal is not to have a single point showing the top of each bar, but overlay the bars with a whole cloud)

1

1 Answers

0
votes

Depends on what you're trying to do you you can use error bars, you can play with the width, thickness and color parameters to make it look like a regular scatter (width refers to the line at the ends and thickness to the whiskers, thickness = 0 should take them out).