在使用ggplot的facet_wrap时缩放y轴

3

我正在尝试在使用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 图,希望更改 B 组和 C 组的 y 轴

1个回答

0

看起来这似乎与四舍五入如何影响您的 my_breaks 函数的结果有关。如果您删除 round,使您的函数如下所示

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。

谢谢!我能通过以下方式纠正低值问题: 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){ifelse(x<0.015, round(x,3), round(x,2))}) - user3196167

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接