简体   繁体   English

ggplot2,将两个比例应用于同一个情节? 自上而下的barplot

[英]ggplot2, applying two scales to the same plot? Top down barplot

See plot here: 看这里的情节:

在此输入图像描述 (from here ) (从这里

How do I reproduce both the upper and lower portion of the barplot using ggplot2? 如何使用ggplot2重现条形图的上部和下部?

For example, I can produce the upper portion with 例如,我可以生产上部

ggplot(data.frame(x=rnorm(1000, 5)), aes(x=x)) + geom_bar() + scale_y_reverse()

However now if I add any other geom_ , such as another geom_bar() the scale for y is reversed. 但是现在如果我添加任何其他geom_ ,例如另一个geom_bar() ,y的比例将被反转。 Is it possible to apply the scale_y_reverse() to only a specific geom_ ? 是否可以将scale_y_reverse()仅应用于特定的geom_

Another option is to make two separate plots and combine them with arrangeGrob from the gridExtra package. 另一种选择是让两个独立的地块,并结合他们arrangeGrobgridExtra包。 After playing with the plot margins, you can arrive at something that looks decent. 玩完情节边后,你可以得到看起来不错的东西。

library(gridExtra)
library(ggplot2)

set.seed(100)
p2 <- ggplot(data.frame(x=rnorm(1000, 5)), aes(x=x)) + geom_bar() + theme(plot.margin=unit(c(0,0,0,0), 'lines'))
p1 <- p2 + scale_y_reverse() + 
    theme(plot.margin=unit(c(0, 0, -.8, 0), 'lines'), axis.title.x=element_blank(), 
          axis.text.x=element_blank(), axis.ticks.x=element_blank())

p <- arrangeGrob(p1, p2)
print(p)

在此输入图像描述

ggplot only like to have one y-axis scale. ggplot只喜欢有一个y轴刻度。 The easiest thing would be to basically reshape your data yourself. 最简单的方法是自己重塑数据。 Here we can use geom_rect to draw the data where ever we like and we can condition it on group time. 在这里,我们可以使用geom_rect在我们喜欢的地方绘制数据,我们可以在组时间内调整它。 Here's an example 这是一个例子

#sample data
dd<-data.frame(
  year=rep(2000:2014, 2), 
  group=rep(letters[1:2], each=15), 
  count=rpois(30, 20)
)

And now we can plot it. 现在我们可以绘制它。 But first, let's define the offset to the top bars by finding the maxima height at a year and adding a bit of space 但首先,让我们通过查找一年的最大高度并添加一些空间来定义顶部柱的偏移量

height <- ceiling(max(tapply(dd$count, dd$year, sum))*1.10)

And here's how we plot 这就是我们的情节

ggplot(dd) + 
  geom_rect(aes(xmin=year-.4, xmax=year+.4, 
    ymin=ifelse(group=="a", 0, height-count), 
    ymax=ifelse(group=="a", count, height), fill=group)) + 
  scale_y_continuous(expand=c(0,0))

And that will give us 那会给我们带来好处

在此输入图像描述

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

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