Align x axes of window section and section using ggplot

Im trying to align the x-axis of the line chart and line chart in the same window frame using ggplot. Here is the fake data I'm trying to do this.

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.

+4
source share
2 answers

@ eipi10 answers this particular case, but overall you also need to align the width of the graph. If, for example, the labels y on one of the graphs take up more space than on the other, even if you use the same axis on each graph, they will not line up when transferred 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)

enter image description here

In this case, you need to align the width of the graph:

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)

enter image description here

+5
source

x , scale_x_continuous, ggplot .

My_plot <- ggplot(data = m, aes(x = x, y = y)) + theme_bw() + 
              scale_x_continuous(limits=range(m$x))

, , .

+1

Source: https://habr.com/ru/post/1589483/


All Articles