-->

creating mirrored barplots with distinct scales in

2019-08-24 02:33发布

问题:

I have a follow up to this nice question:

How do you create a bar plot for two variables mirrored across the x-axis in R?

these answers show how to make mirrored barplots in ggplot2 in R where some values are positive and some are negative. my question is: what if you want to use distinct scales for the up and down bars which are both positive? for example if the up bar is condition 1 and down bar is condition 2, and both bars represent values between 1 and 100. I just want the direction of the bar to signify different conditions on these without committing to negative values. Is that possible in ggplot2? thank you

回答1:

You can just change the label using scale_y_continuous():

library(ggplot2)

dat <- data.frame(
  group = rep(c("Above", "Below"), each=10),
  x = rep(1:10, 2),
  y = c(runif(20, 0, 100))
)

dat$y[dat$group=="Below"] <- -dat$y[dat$group=="Below"]

ggplot(dat, aes(x=x, y=y, fill=group)) + 
  geom_bar(stat="identity", position="identity") + 
  scale_y_continuous(breaks=seq(-100,100,by=50),labels=abs(seq(-100,100,by=50)))

If you don't like 50, you can always just change by.



标签: r plot ggplot2