Representing dots in violin chart

Viewed 94

The following code, plots a violin chart with weights associated with the values. The question is, why only one dot is shown? The top is 218*1=218, so a dot at 218 is shown and it is fine. However, for the second and third, it is expected to see two dots at 218*0.1=21.8 and 30*0.9=27.

> library(ggplot2)
> mydata <- read.csv('test.csv', header=T,row.names=1)
> mydata
       V1  V2 V3
P1.K1 218 1.0  R
P2.K1 218 0.1  R
P2.K2  30 0.9  R
> p <- ggplot(mydata, aes(x=V3, y=V1, weight=V2)) + geom_violin(trim=FALSE)
> p + geom_dotplot(binaxis='y', stackdir='center', dotsize=1)
`stat_bindot()` using `bins = 30`. Pick better value with `binwidth`.
>

enter image description here

Any idea about that?

3 Answers

Updated With the help of Waldi, now it should work.

The main thing here is to assign the weighted values to geom_dotplot this will solve Op's issue with only one dot.

library(ggplot2)

#  add V1_weight to mydata
mydata <- mydata %>% 
  mutate(V1_weight= V1*V2)

ggplot(mydata) + 
  geom_violin( mapping = aes(x = V3, y = V1, weight = V2),trim=FALSE) +
  geom_dotplot(aes(x = V3, y=V1_weight), binaxis='y', stackdir='center', dotsize=1) 

enter image description here

data:

structure(list(id = c("P1.K1", "P2.K1", "P2.K2"), V1 = c(218, 
218, 30), V2 = c(1, 0.1, 0.9), V3 = c("R", "R", "R"), V1_weight = c(218, 
21.8, 27)), row.names = c(NA, -3L), class = c("tbl_df", "tbl", 
"data.frame"))

geom_dotplot doesn't have a weight mapping :

library(ggplot2)
ggplot(mydata, ) + geom_violin( mapping = aes(x = V3, y = V1, weight = V2),trim=FALSE) +
                   geom_dotplot(mydata, mapping = aes(x = V3, y = V1),binaxis='y', dotsize=1)

enter image description here

From your comments, t sounds like you want the geom_violin() line from Waldi's answer and the geom_dotplot() line from TarJae's answer:

ggplot(mydata, aes(x = V3)) + 
  geom_violin(aes(y = V1, weight = V2), trim = FALSE) + 
  geom_dotplot(aes(y = V1 * V2), binaxis = 'y', stackdir = 'center', dotsize = 1)

enter image description here

Related