[英]Legend with geom_line and geom_ribbon
我創造了一個數字,我周圍有一條線和信心帶。 為此,我在R中的ggplot2
中使用geom_line
和geom_ribbon
。問題是如何處理圖例。 在其中,添加斜杠,谷歌搜索了一段時間后,我明白這是一個常見的問題。 我發現的大多數解決方案都是用於條形圖(例如ggplot cookbook)。 我也找到了抑制它的解決方案,但這對我沒用。
下面我有三個圖表顯示了這個問題。 首先,當我只繪制線條時,它看起來很好。 然后,當我添加繪圖的功能區部分時,會添加斜杠。 第三個圖是我希望它看起來的樣子(顯然是斜杠)。 我該如何實現這一目標?
編輯:要清楚,我想要的是下圖中的內容(我使用MS Paint修復):
library(ggplot2)
library(gridExtra)
set.seed(1)
y <- sin(seq(1, 2*pi, length.out = 100))
x <- 1:100
plotdata <- data.frame(x=x, y=y, lower = (y+runif(100, -1, -0.5)), upper = (y+runif(100, 0.5, 1)))
h1 <- ggplot(plotdata) + geom_line(aes(y=y, x=x, colour = "sin"))
h2 <- h1 + geom_ribbon(aes(ymin=lower, ymax=upper, x=x, colour = "bands"), alpha = 0.3)
h3 <- h2 + scale_colour_manual(name='', values=c("bands" = "grey", "sin" = "blue"))
grid.arrange(h1, h2, h3)
您可以制作單獨的圖例 - 一個用於線條顏色,另一個用於填充色帶。 然后使用scale_...
將圖例的名稱設置為空白。 唯一的問題是圖例鍵是分開的。
ggplot(plotdata) + geom_line(aes(y=y, x=x, colour = "sin"))+
geom_ribbon(aes(ymin=lower, ymax=upper, x=x, fill = "band"), alpha = 0.3)+
scale_colour_manual("",values="blue")+
scale_fill_manual("",values="grey12")
如果要在圖例上顯示顏色,則可能需要添加一些額外的geom_line
。 不要使用顏色geom_ribbon
,然后添加upper
和lower
線。
h2 <- h1 + geom_ribbon(aes(ymin=lower, ymax=upper, x=x), alpha = 0.3) +
geom_line(aes(x=x, y = lower, color = "bands")) +
geom_line(aes(x=x, y = upper, color = "bands"))
編輯:您還可以使用fill
比例。
h1 <- ggplot(plotdata) + geom_line(aes(y=y, x=x, colour = "sin", fill="sin"))
h2 <- h1 + geom_ribbon(aes(ymin=lower, ymax=upper, x=x, fill="bands"), alpha = 0.3) +
geom_line(aes(x=x, y = lower, color = "bands")) +
geom_line(aes(x=x, y = upper, color = "bands"))
h3 <- h2 + scale_colour_manual(name='', values=c("bands" = "grey", "sin" = "blue")) +
scale_fill_manual(name = '', values=c("bands" = "grey12", "sin" = "grey"))
grid.arrange(h1, h2, h3)
如果您不想要(幾乎不可見)灰線,您還可以在顏色語句中設置"bands" = "transparent"
。
嘗試將顏色保持在aes
之外,然后它將不會顯示在圖例上:
h1 + geom_ribbon(aes(ymin=lower, ymax=upper, x=x), colour = "red", alpha = 0.3)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.