2017-06-20 53 views
0

我希望灰色背景突出顯示與我插入到我的圖中的兩條垂直虛線對齊。我可以將突出顯示與「nd」和「pc」對齊,但我希望背景可以在兩個時間點之間調整(前/後處理)。兩次治療之間的ggplot背景突出顯示

我已經嘗試識別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") 

Current plot

+1

沒有數據或情節,我不知道你看到的... – CPak

+0

請仔細閱讀[如何使R中一個偉大的可重複的例子?(https://開頭計算器.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Masoud

+0

該情節附加到現在的問題...我認爲... – Alex

回答

1

不要與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") 

enter image description here

+0

優秀!謝謝! – Alex

+0

樂意提供幫助,歡迎來到Stack Overflow。如果此答案或任何其他人解決了您的問題,請將其標記爲已接受。 –

0

使用annotategeom = "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") 

enter image description here