简体   繁体   中英

ggplot: position dodge based on category

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)

在此处输入图像描述 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)))

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))

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM