r - 参数比例在 r 中的 ggplot2 中不起作用

标签 r ggplot2

我正在使用 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

enter image description here

然后,我必须使用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  

enter image description here

我的问题是,有没有一种方法可以像使用 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/

相关文章:

r - 使用 R 中的 RegEx 以 Mon、DD、YYYY 格式解析日期

linux - cron 无法运行 R 脚本

r - 在 foreach R 中使用列表

r - 使用 ggplot 绘制辅助轴

r - 在哪里可以找到关于 `fun` 中的 `geom_line` 参数的文档?

r - 在 ggplot2 中设置切面的绝对大小

r - 如何将 stat_ecdf 与 geom_ribbon 结合使用?

r - 在列中查找值返回 TRUE/FALSE

根据 r 列上的两个条件删除重复行

r - R 中离散数据的计算密度