首页 文章

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

提问于
浏览
4

以下代码

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轴仅显示在刻面图的左侧(即第1和第3图的侧面) .

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

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

@Roland还建议在ggplot之外使用 histddply 来获取最大计数 . 是不是有基于 ggplot2 的解决方案?

EDIT: @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")

enter image description here

而现在这一个 .

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

enter image description here

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

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

3 回答

  • 0

    这就是你要追求的吗?

    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)
    
  • 3
    ggplot(m, aes(value)) + 
      facet_wrap(~variable,scales="free") +
      ylim(c(0,30)) +
      geom_histogram()
    
  • 6

    Didzis Elferts在https://stackoverflow.com/a/14584567/2416535中建议使用 ggplot_build() 来获取geom_histogram中使用的bin的值( ggplot_build() 提供 ggplot2 用于绘制图形的数据) . 将图形存储在对象中后,可以在 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
    

    因此,我试图用这个替换max y limit:

    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)))
    

    enter image description here

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

相关问题