facet_wrap equal axis per panel

2020-05-06 11:11发布

I would like to make a plot using facet_wrap where the axes can vary for each panel but within a panel the x and y axes should be the same scale.

e.g. see the following plots

df <- read.table(text = "
x y g
1 5 a
2 6 a
3 7 a
4 8 a
5 9 b
6 10 b
7 11 b
8 12 b", header = TRUE)

library(ggplot2)

ggplot(df, aes(x=x,y=y,g=g)) +
  geom_point() +
  facet_wrap(~ g) # all axes 1-12

ggplot(df, aes(x=x,y=y,g=g)) +
  geom_point() +
  facet_wrap(~ g, scales = "free")
 # fee axes, y & y axes don't match per panel

What i want is for panel a the x and why axes both to be 1-8 and for panel b the x and y axes both to range from 5 - 12.

Is this possible?

标签: r plot ggplot2
3条回答
一夜七次
2楼-- · 2020-05-06 11:20

Using this answer you could try the following:

dummy <- data.frame(x = c(1, 8, 5, 12), y = c(1, 8, 5, 12), g = c("a", "a", "b", "b"))
ggplot(df, aes(x=x,y=y)) +
 geom_point() +
 facet_wrap(~ g, scales = "free") + 
 geom_blank(data = dummy)

enter image description here

查看更多
相关推荐>>
3楼-- · 2020-05-06 11:34

Another solution is trick the axes for individual facet_wrap() plots by adding invisible points to the plots with x and y reversed so that the plotted data is "square", e.g.,

library(ggplot2)
p <- ggplot(data = df) + 
       geom_point(mapping = aes(x = x, y = y)) + 
       geom_point(mapping = aes(x = y, y = x), alpha = 0) + 
       facet_wrap( ~ g, scales = "free")
print(p)

You could also use geom_blank(). You don't need dummy data.

查看更多
趁早两清
4楼-- · 2020-05-06 11:38

This wasn't an option when the question was asked, but these days I would highly recommend patchwork for combining plots.

查看更多
登录 后发表回答