使用ggplot将箱形图和线图的x轴对齐 [英] Align x axes of box plot and line plot using ggplot

查看:924
本文介绍了使用ggplot将箱形图和线图的x轴对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用ggplot在一个窗口框架中对齐柱状图和线图的x轴。这是我正在尝试使用的假数据。

  library(ggplot2)
library(gridExtra)
m< - as.data.frame(matrix (0,ncol = 2,nrow = 27))
colnames(m)<-c(x,y)
for(i in 1:nrow(m))
{
m $ x [i]< - i
m $ y [i]< - ((i * 2)+ 3)
}

My_plot < - (ggplot(data = m,aes(x = x,y = y))+ theme_bw())
Line_plot < - My_plot + geom_line()
Bar_plot< - My_plot + geom_bar(stat =identity)

grid.arrange(Line_plot,Bar_plot)

感谢您的帮助。

解决方案

@ eipi10回答了这个特殊情况,但总的来说,您还需要均衡绘图宽度。例如,如果其中一个图上的y标签占用的空间大于另一个上的空间,即使您在每个图上使用相同的坐标轴,传递给 grid.arrange时也不会排队

  axis < -  scale_x_continuous(限制=范围(m $ x))

Line_plot < - ggplot(data = m,aes(x = x,y = y))+ theme_bw()+ axis + geom_line()

m2 < - 在m),y < - y * 1e7)
Bar_plot <-ggplot(data = m2,aes(x = x,y = y))+ theme_bw()+ axis + geom_bar(stat =identity)

grid.arrange(Line_plot,Bar_plot)

$ b $ pre $ Line_plot< - ggplot_gtable(ggplot_build(Line_plot))
Bar_plot< - ggplot_gtable(ggplot_build(Bar_plot ))

Bar_plot $ widths< -Line_plot $ widths

grid.arrange(Line_plot,Bar_plot)


Im trying to align the x-axes of a bar plot and line plot in one window frame using ggplot. Here is the fake data I'm trying to do it with.

library(ggplot2)
library(gridExtra)
m <- as.data.frame(matrix(0, ncol = 2, nrow = 27))
colnames(m) <- c("x", "y")
for( i in 1:nrow(m))
{
  m$x[i] <- i
  m$y[i] <- ((i*2) + 3)
}

My_plot <- (ggplot(data = m, aes(x = x, y = y)) + theme_bw())
Line_plot <- My_plot + geom_line()
Bar_plot <- My_plot + geom_bar(stat = "identity")

grid.arrange(Line_plot, Bar_plot)

Thank you for your help.

解决方案

@eipi10 answers this particular case, but in general you also need to equalize the plot widths. If, for example, the y labels on one of the plots take up more space than on the other, even if you use the same axis on each plot, they will not line up when passed to grid.arrange:

axis <- scale_x_continuous(limits=range(m$x))

Line_plot <- ggplot(data = m, aes(x = x, y = y)) + theme_bw() + axis + geom_line()

m2 <- within(m, y <- y * 1e7)
Bar_plot <- ggplot(data = m2, aes(x = x, y = y)) + theme_bw() + axis + geom_bar(stat = "identity")

grid.arrange(Line_plot, Bar_plot)

In this case, you have to equalize the plot widths:

Line_plot <- ggplot_gtable(ggplot_build(Line_plot))
Bar_plot <- ggplot_gtable(ggplot_build(Bar_plot))

Bar_plot$widths <-Line_plot$widths 

grid.arrange(Line_plot, Bar_plot)

这篇关于使用ggplot将箱形图和线图的x轴对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆