I am currently creating several box plots using ggplot2
. Every box plot displays similar data, but the ranges of the discrete x axes, as well as the continuous y axes are not always the same. Some box plots only have two discrete x values, others have three or five. In addition, the continuous y axes have very different ranges; some range from 0-80, others from 0-2.5.
Ideally, I would like to get the following output: for every graph, all of the y axes should be the same absolute length, and every discrete "step" along the x axes should be the same absolute length as well.
I have created a simple example using bar graphs instead of box plots that shows the issue:
library(ggplot2)
library(grid)
x1 <- factor(c('a','b','c','d','e'))
y1 <- c(10,20,50,60,80)
df1 <- data.frame(x1,y1)
x2 <- factor(c('a','b'))
y2 <- c(2,3.5)
df2 <- data.frame(x2,y2)
g1 <- ggplot(df1, aes(x = x1, y = y1)) +
geom_bar(stat='identity')
g2 <- ggplot(df2, aes(x=x2,y=y2)) +
geom_bar(stat='identity')
grid.newpage()
pushViewport(viewport(layout = grid.layout(2, 1)))
print(g1, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
print(g2, vp = viewport(layout.pos.row = 2, layout.pos.col = 1))
This gives the following output:
Basically, I would like the bottom graph to be only as wide as the a and b segment of the top graph, thereby making every bar in both graphs the same absolute width. Please note that my graphs will be plotted individually, not as part of a grid.
I have tried playing with the aspect ratio using coord_fixed()
, but since the y axes have such different ranges there is not a consistent value I was able to use for every graph. Adjusting the actual width
of geom_boxplot
alters the relative width of the individual boxes, not their absolute width.
I could potentially use the solution to ggplot2 scale_x_continuous limits or absolute using scale_x_discrete
, but then I would have to crop the second image.
I have also tried to adjust solutions from other questions, such as Setting absolute size of facets in ggplot2, GGPLOT2: Distance of discrete values of from each end of x-axis, and Formatting positions on discrete scale in ggplot2, but none have worked so far.
Any help would be greatly appreciated!
Edit in response to @tonytonov's answer
Adjusting scale_x_discrete
as I mentioned above, and in @tonytonov's answer below, results in the following graph:
However, I would like to just get the bottom part the following graph (I used Inkscape to crop the lower graph):
As mentioned above, I am just plotting the graphs in a grid to show that I would like the absolute lengths of the y axes and the absolute x step lengths to be the same.
Thanks again!