![](/img/trans.png)
[英]ggplot2 - How to boxplot two variables with different scales on same plot using a primary and secondary y-axis?
[英]ggplot2, applying two scales to the same plot? Top down barplot
看这里的情节:
(从这里 )
如何使用ggplot2重现条形图的上部和下部?
例如,我可以生产上部
ggplot(data.frame(x=rnorm(1000, 5)), aes(x=x)) + geom_bar() + scale_y_reverse()
但是现在如果我添加任何其他geom_
,例如另一个geom_bar()
,y的比例将被反转。 是否可以将scale_y_reverse()
仅应用于特定的geom_
?
另一种选择是让两个独立的地块,并结合他们arrangeGrob
从gridExtra包。 玩完情节边后,你可以得到看起来不错的东西。
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只喜欢有一个y轴刻度。 最简单的方法是自己重塑数据。 在这里,我们可以使用geom_rect
在我们喜欢的地方绘制数据,我们可以在组时间内调整它。 这是一个例子
#sample data
dd<-data.frame(
year=rep(2000:2014, 2),
group=rep(letters[1:2], each=15),
count=rpois(30, 20)
)
现在我们可以绘制它。 但首先,让我们通过查找一年的最大高度并添加一些空间来定义顶部柱的偏移量
height <- ceiling(max(tapply(dd$count, dd$year, sum))*1.10)
这就是我们的情节
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))
那会给我们带来好处
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.