7

以下代码

library(ggplot2)
library(reshape2)

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

ggplot(m, aes(value)) + 
  facet_wrap(~variable,ncol=2,scales="free_x") +
  geom_histogram()

生成 4 个具有固定 y 轴的图(这是我想要的)。但是,默认情况下,y 轴仅显示在多面图的左侧(即第一和第三图的一侧)。

我该怎么做才能使 y 轴在所有 4 个图表上显示出来?谢谢!

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

@Roland 还建议在 ggplot 之外使用histandddply来获得最大计数。没有任何ggplot2基础的解决方案吗?

编辑: @babptiste 有一个非常优雅的解决方案。然而,当改变 binwidth 时,它开始表现得很奇怪(至少对我来说)。使用默认 binwidth (range/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")

在此处输入图像描述

而现在这个。

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

在此处输入图像描述

binwidth 现在设置为 0.5,因此最高频率应该会改变(实际上会降低,因为在更紧凑的 bin 中观察会更少)。然而,y 轴没有发生任何事情,它仍然覆盖相同数量的值,在每个图中创建了一个巨大的空白空间。

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

4

3 回答 3

8

这就是你所追求的吗?

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)
于 2013-07-01T14:16:46.257 回答
3
ggplot(m, aes(value)) + 
  facet_wrap(~variable,scales="free") +
  ylim(c(0,30)) +
  geom_histogram()
于 2013-07-01T09:18:28.750 回答
0

https://stackoverflow.com/a/14584567/2416535中的 Didzis Elferts建议使用ggplot_build()来获取 geom_histogram 中使用的 bin 的值(ggplot_build()提供用于ggplot2绘制图形的数据)。将图形存储在对象中后,您可以在列中找到所有 bin 的值count

library(ggplot2)
library(reshape2)

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

plot = ggplot(m) + 
  facet_wrap(~variable,scales="free") +
  geom_histogram(aes(x=value))

ggplot_build(plot)$data[[1]]$count

因此,我尝试通过以下方式替换最大 y 限制:

max(ggplot_build(plot)$data[[1]]$count)

并设法得到一个工作示例:

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

bin=0.5 # you can use this to try out different bin widths to see the results

plot=
  ggplot(m) + 
  facet_wrap(~variable,scales="free") +
  geom_histogram(aes(x=value),binwidth=bin)

ggplot(m) + 
  facet_wrap(~variable,ncol=2,scales="free") +
  geom_histogram(aes(x=value),binwidth=bin) +
  ylim(c(0,max(ggplot_build(plot)$data[[1]]$count)))

在此处输入图像描述

它完成了这项工作,尽管很笨拙。如果有人对此进行改进以消除创建 2 个图表的需要,或者更确切地说是两次相同的图表,那就太好了。

于 2013-07-01T13:09:43.243 回答