r - 在 ggplot 中使用 facet_wrap 时缩放 y 轴

标签 r ggplot2

我尝试在使用 facet_wrap 时组合不同的 y 轴,但我希望所有 y 轴根据该比例的最小值和最大值有 3 个断点,即 0、中点和最大值。它适用于小平面网格上的一些图,但不适用于所有图。

这是当前代码:

# data table, in long format 
dt = structure(list(Grp = c(rep("GroupA",12),rep("GroupB",12),rep("GroupC",12),rep("GroupD",12)), Type = c(rep(c(rep("Type1",5),rep("Type2",7)),4)), XVal = c(2L, 3L, 4L, 5L, 6L,
1L, 2L, 3L, 4L, 5L, 6L, 7L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L,
5L, 6L, 7L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 2L,
3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L, 7L), YVal = c(0.2417, 0.2156, 0.264, 
0.2805, 0.2414, 0.2882, 0.0825, 0.0561, 0.1443, 0.1074, 0.0252, 
1e-04, 0.0186, 0.0157, 0.0473, 0.13, 0.1205, 0.0689, 0.1506, 
0.2945, 0.3098, 0.1474, 0.3408, 0.1327, 0.0102, 0.0033, 0.0021, 
2e-04, 0, 0.0124, 0.0053, 0.0039, 0.0014, 4e-04, 0, 0, 0.0574, 
0.1003, 0.0687, 0.0976, 0.1067, 0.1161, 0.0964, 0.0517, 0.0658, 
0.0654, 0.0241, 0.0021)), row.names = c(NA,-48L), class = "data.frame")

# first created a function to define three breaks, and round to 2 decimal points
my_breaks <- function(y) {round(seq(0, max(y),length.out = 3),2)}

# use that function in the 'scale_y_continuous' while specifying that the y scale is "free" in facet_wrap 
ggplot(dt,aes(x=XVal,y=YVal)) + geom_line(aes(color=Type)) +
  facet_wrap(~Grp,scales = "free_y", ncol = 2) +
  scale_y_continuous(breaks = my_breaks)

休息是我想要的 A 和 D 组,而不是 B 和 C。任何帮助将不胜感激。

Facet_wrap plot, looking to change y-axis for Groups B & C

最佳答案

它看起来与舍入如何影响 my_breaks 函数的结果有关。如果你删除圆形,那么你的函数看起来像

my_breaks <- function(y) {seq(0, max(y),length.out = 3)}

每个刻面恰好有三个均匀间隔的断裂。现在我们可以格式化图中的数字:

ggplot(dt,aes(x=XVal,y=YVal)) + geom_line(aes(color=Type)) +
      facet_wrap(~Grp,scales = "free_y", ncol = 2) +
      scale_y_continuous(breaks = my_breaks,
                         labels = function(x){round(x,2)})

enter image description here

请注意,但是在 C 组中,标签最终没有完全意义,因为中断的两个值(0.013 和 0.006)都四舍五入为 0.01。

关于r - 在 ggplot 中使用 facet_wrap 时缩放 y 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58492265/

相关文章:

r - 在 R 中暂停和恢复插入符训练

r - 为什么这个 CSV 数据与 ggplot2 晶须图复杂化?

r - ggplot2 中 geom_point 的黑星符号

r - 多重 geom_sf 色彩美学(离散+连续)

r - 使用不包含字符串的正则表达式过滤 Shiny 的DT

r - 使用带有替换函数的 get()

r - 如何提取两个字符串之间的数字?

r - 如何使用 gml 格式文件将 igraph 边缘属性设置为字符串?

r - 使用 geom_segment 按因素分组数据

r - 如何抖动/删除 geom_text 标签的重叠