Ggplot2: set absolute distance to discrete point x

I am currently creating several graphs using ggplot2. Each square displays similar data, but the ranges of discrete x-axes, as well as continuous y-axes, are not always the same. Some graphs have only two discrete values ​​of x, while others have three or five. In addition, continuous y axes have very different ranges; some range from 0 to 80, others from 0-2.5.

Ideally, I would like to get the following result: for each graph, all y axes should be the same absolute length, and each discrete "step" along the x axes should be the same absolute length.

I created a simple example using histograms instead of graphs that show the problem:

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 result:

enter image description here

, , , a b , . , , .

coord_fixed(), y , , . width geom_boxplot , .

ggplot2 scale_x_continuous limit absolute scale_x_discrete, .

, ggplot2, GGPLOT2: x ggplot2, .

!

@tonytonov answer

scale_x_discrete, , @tonytonov , :

enter image description here

( Inkscape ):

enter image description here

, , , , y x .

!

+4
1

"" , scale_x_discrete(limits = ) , ,

g2 + xlim(levels(df1$x1))

pushViewport : , gridExtra.

library(gridExtra)
grid.arrange(g1, g2 + xlim(levels(df1$x1)), nrow = 2)

enter image description here

, , . .

EDIT:

, , (rectGrob placeholder)

grid.arrange(g1, g2, rectGrob(width = NA), 
             layout_matrix = rbind(c(1,1,1,1,1), c(2,2,3,3,3)))

, x, ( wiki ). - @baptiste:)

enter image description here

+1

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


All Articles