我想使用 R 包
ggbreak
在此图中的 Y 轴上添加一个断点,更具体地说是下面板中的条形图。然而,当我将函数 scale_y_break()
包含在所需的中断值中时,它完全弄乱了图形。
这是可生产的示例和数字:
library(dplyr)
library(ggplot2)
library(ggbreak)
set.seed(2024)
# Create a dataframe to mimic your data structure
df <- data.frame(
method = rep(rep(c("m1", "m2", "m3", "m4", "m5"), each = 3),2),
type = rep(c("A", "B"), each = 15),
subtype = rep(c("a", "b", "c"), 10),
mean = c(0.56, 0.18, 0.54, 0.59, 0.15,
1.47, 0.31, 1.45, 0.76, 0.21,
1.64, 0.91, 1.89, 1.27, 0.38,
5.61, 1.41, 0.93, 1.06, 0.42,
0.45, 0.98, 1.00, 0.81, 4.06,
1.64, 0.91, 1.89, 1.27, 0.38) * 0.2
)
ggplot(df, aes(x = method, y = mean*100, fill = subtype)) +
geom_bar(stat = "identity", position = position_dodge(0.8), width = 0.7) +
facet_wrap(~type, ncol = 1, scales = "free_y", strip.position="top") +
theme_bw()+
theme(legend.position = "bottom")
现在如果我加上休息时间:
ggplot(df, aes(x = method, y = mean*100, fill = subtype)) +
geom_bar(stat = "identity", position = position_dodge(0.8), width = 0.7) +
facet_wrap(~type, ncol = 1, scales = "free_y", strip.position="top") +
theme_bw()+
theme(legend.position = "bottom") +
scale_y_break(c(60, 150))
问题是什么以及如何解决?
您可以添加
coord_flip()
以获得水平条。如果您不希望每个框上都有重复的分面标题,请添加 strip.position="right"
。
ggplot(df, aes(x = method, y = mean*100, fill = subtype)) +
coord_flip() +
geom_bar(stat = "identity", position = position_dodge(0.8), width = 0.7) +
facet_wrap(~type, ncol = 1, scales = "free_y", strip.position="right") +
theme_bw()+
theme(legend.position = "bottom") +
scale_y_break(c(60, 90))
或者使用 2 列作为 A 和 B,并删除
scales = "free_y"
:
ggplot(df, aes(x = method, y = mean*100, fill = subtype)) +
# coord_flip() +
geom_bar(stat = "identity", position = position_dodge(0.8), width = 0.7) +
facet_wrap(~type, ncol = 2, strip.position="top") +
theme_bw()+
theme(legend.position = "bottom") +
scale_y_break(c(60, 90))