简体   繁体   English

ggplot2:将geom_bar基线设置为1而不是零

[英]ggplot2: Setting geom_bar baseline to 1 instead of zero

I'm trying to make a bar graph (with geom_bar) of ratios, and would like to set the x-axis at y=1. 我正在尝试制作比率的条形图(使用geom_bar),并希望将x轴设置为y = 1。 Therefore, ratios <1 would be below the axis and ratios >1 would be above the axis. 因此,比率<1将在轴下方,比率> 1将在轴上方。 I can do something similar with geom_point: 我可以用geom_point做类似的事情:

ggplot(data, aes(x=ratio, y=reorder(place,ratio)))+geom_point()+geom_vline(xintercept=1.0)+coord_flip()

However geom_bar would be much preferred... Ideally the graph would look something like this: http://i.stack.imgur.com/isdnw.png , except the "negative" bars would be ratios <1. 但是,geom_bar将是更可取的...理想情况下,图形应如下所示: http : //i.stack.imgur.com/isdnw.png ,除了“负数”条的比率为<1。

Thanks so much for your help! 非常感谢你的帮助!

C C

You can shift the geom_bar baseline to 1 (instead of zero) as follows: 您可以按以下方式将geom_bar基线移至1(而不是零):

  1. Shift the data by -1, so that ratio=1 becomes zero and is therefore used as the baseline. 将数据移动-1,使ratio=1变为零,因此用作基线。

  2. Add 1 to the y-axis labels so that they reflect the actual data values. 在y轴标签上加1,以便它们反映实际数据值。

     dat = data.frame(ratio=-4:11/3, x=1:16) ggplot(dat, aes(x, ratio-1, fill=ifelse(ratio-1>0,"GT1","LT1"))) + geom_bar(stat="identity") + scale_fill_manual(values=c("blue","red"), name="LT or GT 1") + scale_y_continuous(labels = function(y) y + 1) 

在此处输入图片说明

A second approach to consider is to use geom_segment . 要考虑的第二种方法是使用geom_segment This allows you to keep the 'original' y-axis. 这使您可以保持“原始” y轴。

set.seed(123)
dat <- data.frame(x=1:10, ratio=sort(runif(10,0,2)))

#create flag
dat$col_flag <- dat$ratio > 1

ggplot(dat, aes(color=col_flag)) +
  geom_segment(aes(x=x,xend=x,y=1, yend=ratio), size=15)

在此处输入图片说明

We can do this with a custom transformation of the y-scale: 我们可以通过y缩放的自定义转换来做到这一点:

shift_trans = function(d = 0) {
  scales::trans_new("shift", transform = function(x) x - d, inverse = function(x) x + d)
}

ggplot(dat, aes(x, ratio, fill = ifelse(ratio > 1,"GT1","LT1"))) +
  geom_bar(stat="identity") +
  scale_fill_manual(values=c("blue","red"), name="LT or GT 1") +
  scale_y_continuous(trans = shift_trans(1))

在此处输入图片说明

This approach is nicely general and is parmaterized. 这种方法非常通用,并且已被参数化。


Using the data eipi10's answer: dat = data.frame(ratio=-4:11/3, x=1:16) 使用数据eipi10的答案: dat = data.frame(ratio=-4:11/3, x=1:16)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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