R ggplot两种处理之间的背景突出显示

R ggplot两种处理之间的背景突出显示,r,ggplot2,R,Ggplot2,我希望灰色背景高亮显示与插入到绘图中的两条垂直虚线对齐。我可以让高光与“nd”和“pc”对齐,但我希望背景在两个时间点之间对齐(治疗前/治疗后) 我尝试将高光的边界标识为x=1.5和4.5,就像我对虚线所做的那样,但是我得到了“错误:离散值提供给连续比例” 数据: 我目前的代码如下: ggplot(LipCon, aes(x = ChillTime, y = Lipid)) + theme_bw() + labs(x = 'Time (weeks)', y = 'Lipid Conten

我希望灰色背景高亮显示与插入到绘图中的两条垂直虚线对齐。我可以让高光与“nd”和“pc”对齐,但我希望背景在两个时间点之间对齐(治疗前/治疗后)

我尝试将高光的边界标识为x=1.5和4.5,就像我对虚线所做的那样,但是我得到了
“错误:离散值提供给连续比例”

数据:

我目前的代码如下:

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")

不要用
aes
这样写:

几何校正(aes(xmin=1.5,xmax=4.5,ymin=-Inf,ymax=Inf),alpha=0.6,fill=“grey90”)

写下以下内容:

geom\u 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")

使用
注释
geom=“rect”
将单个矩形添加到绘图中,而不是将多个矩形放在彼此的顶部

为了避免在使用矩形层作为第一个打印层时创建连续比例而不是离散比例的问题,可以使用
geom_blank
作为第一个geom层

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")

没有数据或曲线图,我不知道你看到了什么……请阅读随问题附上的曲线图。。。我认为…我认为你的问题与这个非常相关:或者这个:希望这是一种有用的数据格式,MasoudExcellent!谢谢很高兴提供帮助,欢迎使用Stack Overflow。如果此答案或任何其他答案解决了您的问题,请将其标记为已接受。
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")