我希望灰色背景突出显示与我插入到我的情节中的两条垂直虚线对齐。我可以突出显示与#34; nd"和" pc",但我希望背景在两个时间点之间对齐(治疗前/后)。
我已经尝试将高光的边框识别为x = 1.5和4.5,就像我用虚线所做的那样,但我得到了"Error: Discrete value supplied to continuous scale"
。
数据:
> dput(LipCon)
structure(list(ChillTime = structure(c(1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L), .Label = c("nd",
"6", "13", "24", "pc"), class = "factor"), Lipid = c(30.85703644,
21.91554596, 25.19641351, 56.05474457, 43.02224726, 31.93075251,
21.50358848, 28.74947619, 31.81816769, 30.68972065, 26.63482725,
39.6305118, 29.90226926, 24.28663997, 23.10808485, 30.8010717,
23.78336938, 18.92581619, 24.73146066, 22.48963284)), .Names = c("ChillTime",
"Lipid"), row.names = c(NA, -20L), class = "data.frame")
我目前的代码如下:
ggplot(LipCon, aes(x = ChillTime, y = Lipid)) +
theme_bw() +
labs(x = 'Time (weeks)', y = 'Lipid Content (%)') +
ggtitle("Lipid Content") +
theme(plot.title = element_text(hjust = 0.5, face='bold')) +
geom_rect(aes(xmin = 'nd', xmax = 'pc', ymin=-Inf, ymax=Inf), alpha=0.6, fill="grey90") +
geom_boxplot() +
geom_vline(aes(xintercept=1.5), linetype="dashed") +
geom_vline(aes(xintercept=4.5), linetype="dashed")
答案 0 :(得分:2)
不要使用aes
:
geom_rect(aes(xmin = 1.5, xmax = 4.5, ymin=-Inf, ymax=Inf), alpha=0.6, fill="grey90")
改为写下:
geom_rect(xmin = 1.5, xmax = 4.5, ymin=-Inf, ymax=Inf, alpha=0.6, fill="grey90")
使用aes
强制您的矩形符合绘制LipCon
的刻度,其中x轴对于箱线图是离散的。省略aes
部分可以使您摆脱此约束,因此您可以使用标量在x轴上绘制以指示轴上的确切位置。
完整代码
ggplot(LipCon, aes(x = ChillTime, y = Lipid)) +
theme_bw() +
labs(x = 'Time (weeks)', y = 'Lipid Content (%)') +
ggtitle("Lipid Content") +
theme(plot.title = element_text(hjust = 0.5, face='bold')) +
geom_rect(xmin = 1.5, xmax = 4.5, ymin=-Inf, ymax=Inf, alpha=0.6, fill="grey90") +
geom_boxplot() +
geom_vline(aes(xintercept=1.5), linetype="dashed") +
geom_vline(aes(xintercept=4.5), linetype="dashed")
答案 1 :(得分:0)
将annotate
与geom = "rect"
一起使用,可以将单个矩形添加到绘图中,而不是将多个矩形添加到彼此之上。
要避免在使用矩形图层作为第一个绘图图层时创建连续比例而不是离散比例的问题,可以使用geom_blank
作为第一个几何图层。
ggplot(LipCon, aes(x = ChillTime, y = Lipid)) +
geom_blank() +
theme_bw() +
labs(x = 'Time (weeks)', y = 'Lipid Content (%)') +
ggtitle("Lipid Content") +
theme(plot.title = element_text(hjust = 0.5, face='bold')) +
annotate(geom = "rect", xmin = 1.5, xmax = 4.5, ymin = -Inf, ymax = Inf, alpha = 0.6, fill = "grey90") +
geom_boxplot() +
geom_vline(aes(xintercept=1.5), linetype="dashed") +
geom_vline(aes(xintercept=4.5), linetype="dashed")