将coord_flip()应用于单个图层

时间:2013-09-07 23:33:38

标签: r ggplot2

我想在我的直方图下面有一个显示相同分布的箱线图。 几乎下面的代码可以使用,但coord_flip()正在应用于所有图层,而不仅仅是geom_boxplot图层。

plot1<-ggplot(newdatahistogram, aes_string(x=newdatahistogram[RawLocation])) + 
          xlab(GGVar) + ylab("Proportion of Instances") + 
          geom_histogram(aes(y=..density..), binwidth=1, colour="black", fill="white",origin=-0.5) + 
          scale_x_continuous(limits=c(-3,6), breaks=seq(0,5,by=1), expand=c(.01,0)) +
          geom_boxplot(aes_string(x=-1, y=newdatahistogram[RawLocation])) + coord_flip()

如何将coord_flip()应用于单个图层?

谢谢!

2 个答案:

答案 0 :(得分:2)

我让它与一个黑客一起工作;

plot1 <- ggplot(newdatahistogram, aes_string(x=newdatahistogram[RawLocation], fill=(newdatahistogram[,"PQ"]))) + 
  xlab(GGVar) + ylab("Proportion of Observation") + 
  geom_histogram(aes(y=..density..), binwidth=1, colour="black", origin=-0.5) +
  scale_x_continuous(limits=c(-1,6), breaks=seq(0,5,by=1), expand=c(.01,0)) +
  scale_y_continuous(limits=c(-.2,1), breaks=seq(0,1,by=.2))
  theme(plot.margin = unit(c(0,0,0,0), "cm"))      

plot_box <- ggplot(newdatahistogram) +
  geom_boxplot(aes_string(x=1, y=newdatahistogram[RawLocation])) + 
  scale_y_continuous(breaks=(0:5), labels=NULL, limits=c(-1,6), expand=c(.0,-.03)) + 
  scale_x_continuous(breaks=NULL) + xlab(NULL) + ylab(NULL) +
  coord_flip() + theme_bw() +  
  theme(plot.margin = unit(c(0,0,.0,0), "cm"),
        line=element_blank(),text=element_blank(),
        axis.line = element_blank(),title=element_blank(), panel.border=theme_blank())

PB = ggplotGrob(plot_box)
plot1 <- plot1 + annotation_custom(grob=PB, xmin=-1.01, xmax=5.95, ymin=-.3,ymax=0)

这会将旋转的箱形图保存为grob对象,并将其插入直方图下的绘图中。

我需要稍微使用扩展元素来使刻度排列, 但它的确有效!

说真的,我认为ggplot应该有一个水平的boxplot,没有cord_flip()......我试着编辑boxplot代码,但这对我来说太难了!

尝试发布图片,但信誉不足

答案 1 :(得分:1)

您不能:coord_flip始终作用于所有图层。但是,您有两种选择:

  • 解决方案here显示了如何使用grid.arrange()添加边缘直方图。 (问题中的评论也链接到一个很好的基础R方式来做同样的事情)
  • 您可以使用plot1 + geom_rug(sides='r')

    的地图四边的地毯图来指示密度

    ggplot(mpg,aes(x = class,y = cty))+   geom_boxplot()+ geom_rug(sides =“r”)

enter image description here