facet_wrap:当scale ="free_x"时,如何将y轴添加到每个单独的图形中?

jak*_*kub 5 r ggplot2

以下代码

library(ggplot2)
library(reshape2)

m=melt(iris[,1:4])

ggplot(m, aes(value)) + 
  facet_wrap(~variable,ncol=2,scales="free_x") +
  geom_histogram()
Run Code Online (Sandbox Code Playgroud)

产生4个固定y轴的图形(这就是我想要的).但是,默认情况下,y轴仅显示在刻面图的左侧(即第1和第3图的侧面).

如何使y轴在所有4个图形上显示?谢谢!

编辑:正如@Roland所建议的,可以设置scales="free"和使用ylim(c(0,30)),但我不希望每次都手动设置限制.

@Roland还建议使用histddply外界ggplot的,以获得最大数量.没有任何ggplot2基础解决方案吗?

编辑: @babptiste有一个非常优雅的解决方案.但是,当更改binwidth时,它开始表现得很奇怪(至少对我而言).使用默认binwidth(范围/ 30)检查此示例.y轴上的值介于0到30,000之间.

library(ggplot2)
library(reshape2)

m=melt(data=diamonds[,c("x","y","z")])

ggplot(m,aes(x=value)) + 
  facet_wrap(~variable,ncol=2,scales="free") +
  geom_histogram() +
  geom_blank(aes(y=max(..count..)), stat="bin")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

而现在这一个.

ggplot(m,aes(x=value)) + 
  facet_wrap(~variable,scales="free") +
  geom_histogram(binwidth=0.5) +
  geom_blank(aes(y=max(..count..)), stat="bin")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

binwidth现在设置为0.5,因此最高频率应该改变(实际上减少,因为在更紧密的箱中会有更少的观测值).但是,y轴没有发生任何变化,它仍然覆盖相同数量的值,在每个图形中创建了一个巨大的空白空间.

[问题解决了......请参阅@ baptiste编辑的答案.]

bap*_*ste 6

这就是你要追求的吗?

ggplot(m, aes(value)) + 
  facet_wrap(~variable,scales="free") +
  geom_histogram(binwidth=0.5) +
  geom_blank(aes(y=max(..count..)), stat="bin", binwidth=0.5)
Run Code Online (Sandbox Code Playgroud)