Home > Blockchain >  R ggplot2 : geom_jitter and fill, problem to have the dots on the right boxplot
R ggplot2 : geom_jitter and fill, problem to have the dots on the right boxplot

Time:12-09

Here's my R code

ggplot(dat = Table, aes(x = Group, y = value, fill = Type))  
    geom_boxplot(alpha=0.08) 
    geom_jitter() 
    scale_fill_brewer(palette="Spectral") 
    theme_minimal()

enter image description here

Like you can see the dots are in the middle of the boxplots. What can I add in geom_jitter to have each point in the righ boxplot and not in the middle like this ? I also tried geom_point, it gave the same result !


Thanks to the help now It works, but I wanted to add a line to connect the dots and I got this.. can someone tell how to really connect the dots with lines

enter image description here

CodePudding user response:

I think if you group by interaction(Group, Type) and use position_jitterdodge() you should get what you're looking for.

ggplot(mtcars, aes(as.character(am), mpg, color = as.character(vs),
                   group = interaction(as.character(vs), as.character(am))))  
  geom_boxplot()  
  geom_jitter(position = position_jitterdodge())  # same output with geom_point()

enter image description here


Edit - here's an example with manual jittering applied to data where the each subject appears once in each Group.

I looked for a built-in way to do this, and enter image description here

CodePudding user response:

Best to use position_dodge instead if you want them to line up:

library(ggplot2)

Table <- tibble::tibble(
  Group = rep(c("A", "B"), each = 20),
  Type = factor(rep(c(1:2, 1:2), each = 10)),
  value = rnorm(40, mean = 10)
)

ggplot(dat = Table, aes(x = Group, y = value, fill = Type))  
  geom_boxplot(alpha=0.08) 
  geom_point(position = position_dodge(width = 0.75)) 
  scale_fill_brewer(palette="Spectral") 
  theme_minimal()

To add a line, make sure group = ID goes in both the geom_point and geom_line calls:

library(ggplot2)

Table <- tibble::tibble(
  Group = rep(c("A", "B"), each = 20),
  Type = factor(rep(c(1:2, 1:2), each = 10)),
  ID = factor(rep(1:20, times = 2)),
  value = rnorm(40, mean = 10)
)

ggplot(dat = Table, aes(x = Group, y = value, fill = Type))  
  geom_boxplot(alpha = 0.08)  
  geom_point(aes(group = ID), position = position_dodge(width = 0.75)) 
  geom_line(aes(group = ID), position = position_dodge(width = 0.75), colour = "grey") 
  scale_fill_brewer(palette = "Spectral")  
  theme_minimal()

  • Related