我有一個dat包含兩列 1)Month和 2)的資料框 ( ) Value。我想通過在 x 軸上用兩條斜線中斷 x 軸來強調 x 軸在我的箱線圖中不連續,這些斜線在斜線之間是空的。
示例資料和箱線圖
library(ggplot2)
set.seed(321)
dat <- data.frame(matrix(ncol = 2, nrow = 18))
x <- c("Month", "Value")
colnames(dat) <- x
dat$Month <- rep(c(1,2,3,10,11,12),3)
dat$Value <- rnorm(18,20,2)
ggplot(data = dat, aes(x = factor(Month), y = Value))
geom_boxplot()
labs(x = "Month")
theme_bw()
theme(panel.grid = element_blank(),
text = element_text(size = 16),
axis.text.x = element_text(size = 14, color = "black"),
axis.text.y = element_text(size = 14, color = "black"))
理想的數字如下所示。如何在 ggplot 中制作這個不連續的軸?

uj5u.com熱心網友回復:
我認為有可能得到你想要的。這可能需要一些作業。
這是你的圖表:
library(ggplot2)
set.seed(321)
dat <- data.frame(matrix(ncol = 2, nrow = 18))
x <- c("Month", "Value")
colnames(dat) <- x
dat$Month <- rep(c(1,2,3,10,11,12),3)
dat$Value <- rnorm(18,20,2)
p <- ggplot(data = dat, aes(x = factor(Month), y = Value))
geom_boxplot()
labs(x = "Month")
theme_bw()
theme(panel.grid = element_blank(),
text = element_text(size = 16),
axis.text.x = element_text(size = 14, color = "black"),
axis.text.y = element_text(size = 14, color = "black"))
這是我的努力:
p annotate("segment", x = c(3.3, 3.5), xend = c(3.6, 3.8), y = c(14, 14), yend = c(15, 15))
coord_cartesian(clip = "off", ylim = c(15, 25))
得到這樣的東西:

如果你想走得更遠,可能需要多次嘗試才能做到正確:
p annotate("segment", x = c(3.3, 3.5), xend = c(3.6, 3.8), y = c(14, 14), yend = c(15, 15))
annotate("segment", x = c(0, 3.65), xend = c(3.45, 7), y = c(14.55, 14.55), yend = c(14.55, 14.55))
coord_cartesian(clip = "off", ylim = c(15, 25))
theme_classic()
theme(axis.line.x = element_blank())
只需用兩條新線替換軸。這是一個粗略的想法,可能需要一些時間才能使其完美。

uj5u.com熱心網友回復:
你可以使用facet_wrap. 如果您將前 3 個月分配給一組,將其他月份分配給另一組,那么您可以生成兩個并排并使用單個 y 軸的圖。
這并不完全是您想要的,但它會有效地顯示資料,并突出顯示 x 軸不連續的事實。
dat$group[dat$Month %in% c("1", "2", "3")] <- 1
dat$group[dat$Month %in% c("10", "11", "12")] <- 2
ggplot(data = dat, aes(x = factor(Month), y = Value))
geom_boxplot()
labs(x = "Month")
theme_bw()
theme(panel.grid = element_blank(),
text = element_text(size = 16),
axis.text.x = element_text(size = 14, color = "black"),
axis.text.y = element_text(size = 14, color = "black"))
facet_wrap(~group, scales = "free_x")
* 圖中的差異可能是由于使用不同版本的 Rset.seed導致的結果不同

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315835.html
上一篇:如何在使用ggplot2制作的圖中最小化由patchwork包的guide_area()函式創建的空白空間?
下一篇:R-ggplot行和列
