[英]scaling y-axes while using facet_wrap in ggplot
我正在嘗試在使用 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。 任何幫助將不勝感激。
看起來它與舍入如何影響 my_breaks function 的結果有關。 如果你去掉圓形,那么你的 function 看起來像
my_breaks <- function(y) {seq(0, max(y),length.out = 3)}
每個刻面恰好有三個均勻間隔的斷點。 現在我們可以格式化 plot 中的數字:
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)})
但是請注意,在組 C 中,標簽最終沒有完全意義,因為中斷的兩個值(0.013 和 0.006)都舍入到 0.01。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.