在R中的ggplot2中创建具有不同比例的镜像条形图 [英] creating mirrored barplots with distinct scales in ggplot2 in R

查看:173
本文介绍了在R中的ggplot2中创建具有不同比例的镜像条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很好的问题:

你如何为R中的x轴镜像的两个变量创建条形图?

这些答案显示了如何在R中的ggplot2中制作镜像条形图,其中一些值是正值,一些是负值。我的问题是:如果你想使用不同比例的上下线条都是正值?例如,如果向上条是条件1,向下条是条件2,并且两个条都表示1到100之间的值。我只是希望条的方向表示不同的条件而不承诺为负值。 ggplot2中可能吗?谢谢

您可以使用scale_y_continuous()更改标签:

  library(ggplot2)

dat < - data.frame(
group = rep(c(Above,Below)) ,每个= 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)))

如果你不喜欢50,将改为


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

解决方案

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中的ggplot2中创建具有不同比例的镜像条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆