Home > Software engineering >  ggplot: position dodge based on category
ggplot: position dodge based on category

Time:05-24

I'd like to use position dodge to offset one variable in my ggplot chart (in this case banana) and leave the other two variables (red_apple and green_apple) without an offset. Using position_dodge applies the offset to each variable, but I'd like to choose which variables are offset specifically.

library(ggplot2)

data <- data.frame(Place = c(rep('Place_A',30),rep('Place_B',30)),
                   variable =     c(rep(c(rep('red_Apple',10),rep('green_Apple',10),rep('bananna',10)),2)),
                   value = rep(c(1:10,1:10-.05,1:10 .2),2))

dodge = position_dodge(.5)

ggplot(data, aes(Place, value))   
  geom_point(aes(color=variable),position=dodge)

enter image description here Is there for example a way to scale position manually, like how you can do for other aesthetics? This obviously throws an error, but is what I was hoping for...

ggplot(data, aes(Place, value))   
  geom_point(aes(color=variable, position = variable))   
  scale_position_manual(breaks = c('green_Apple','red_Apple','bananna'),
                      values = c(position_dodge(0),position_dodge(0),position_dodge(.5)))

CodePudding user response:

Does this look like what you want?

data$grp = ifelse(data$variable == "bananna", 2, 1)
ggplot(data, aes(Place, value, group = grp))   
  geom_point(aes(color=variable), position = position_dodge(0.5))

enter image description here

  • Related