我正在使用 facet_grid()
绘制多个图。
我设置了 scales = 'free'
,但它不适用于 facet_1 = 'A', facet_2 = 'a'
和 facet_1 = ' b', facet_2 = 'B'
(左上图和右下图)。
x 轴范围对于两个图来说太大了。
df = data.frame(
x = c(0, 1, 0, 1, 0, 60, 0, 60),
y = c(1.5, 0.3, 1.5, 0.3, 1.8, 0.1, 1.8, 0.1),
facet_1 = c('A', 'A', 'B', 'B', 'A', 'A', 'B', 'B'),
facet_2 = c('a', 'a', 'b', 'b', 'b', 'b', 'a', 'a'))
df %>%
ggplot(aes(x = x, y = y)) +
geom_point() +
geom_line() +
facet_grid(facet_1~facet_2, scales = 'free', space = 'free') # scales = 'free_x' also doesn't work
然后,我必须使用patchwork
来重绘。
df1 = df %>% filter(facet_1 == 'A',facet_2 == 'a')
df2 = df %>% filter(facet_1 == 'A',facet_2 == 'b')
df3 = df %>% filter(facet_1 == 'B',facet_2 == 'a')
df4 = df %>% filter(facet_1 == 'B',facet_2 == 'b')
p1 = df1 %>% ggplot(aes(x = x, y = y)) + geom_point() + geom_line()
p2 = df2 %>% ggplot(aes(x = x, y = y)) + geom_point() + geom_line()
p3 = df3 %>% ggplot(aes(x = x, y = y)) + geom_point() + geom_line()
p4 = df4 %>% ggplot(aes(x = x, y = y)) + geom_point() + geom_line()
library(patchwork)
p1+p2+p3+p4
我的问题是,有没有一种方法可以像使用 facet_grid()
在 ggplot 中使用 patchwork
一样绘制绘图?
最佳答案
实现所需结果的一个选择是使用 ggh4x
包,它提供了一些有用的扩展来克服默认 facet_xxx
的一些限制,例如使用 ggh4x::facet_grid2
你可以:
library(ggplot2)
library(ggh4x)
ggplot(df, aes(x = x, y = y)) +
geom_point() +
geom_line() +
facet_grid2(facet_1~facet_2, scales = "free", independent = "all")
关于r - 参数比例在 r 中的 ggplot2 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72956635/