[英]How can I create a legend for confidence interval and line of best fit for a stat_smooth in a lm (ggplot2)
嗨,我有一個很棒的回歸圖,具有 95% 的置信區間和最佳擬合線,但是似乎無法添加圖例,我已經在各個位置嘗試了 aes、scale_colour_manual,但都無濟於事。 到目前為止我的代碼是
ggplot(bats, aes(x=Days, y=AI))+geom_point(size=2, alpha=0.5) +
xlab("Number of survey days") +
ylab("Bat Activity Index")+
stat_smooth( method = "lm", formula = y~x,
size = 1, col = "red", level = 0.95, alpha=0.5)+
theme_light() +
ggtitle("Regression test between Bat Activity Index and number of survey days")
我想要一個圖例來顯示置信區間(陰影區域)和最佳擬合線(紅色)。
提前致謝!
在ggplot2
,創建圖例的方法是在aes()
指定您的美學。 在這種情況下,您需要標記兩種不同的美學: color
應包含一個標記為“最佳擬合線”的值, fill
包含一個標記為“置信區間”的值。
您的數據集中沒有一列適用於這兩種美學,但是如果您在aes(color=..., fill=...)
輸入字符串,則該字符串將用作標簽美學將為您創造。 當我使用與您自己的格式匹配的虛構數據集時,請觀察下面的工作原理。 特別注意col="red"
已從原始代碼中刪除。 如果它沒有被刪除,它將覆蓋我們放置在aes()
的color=
。
library(ggplot2)
set.seed(1234)
bats <- data.frame(
Days=sample(1:30, 200, replace=TRUE),
AI=rnorm(200, mean=50, sd=20)
)
p <-
ggplot(bats, aes(x=Days, y=AI))+geom_point(size=2, alpha=0.5) +
xlab("Number of survey days") +
ylab("Bat Activity Index")+
stat_smooth(
aes(color="Line of Best Fit", fill="Confidence Interval"),
method = "lm", formula = y~x, size = 1,
level = 0.95, alpha=0.5
)+
theme_light() +
ggtitle("Regression test between Bat Activity Index and number of survey days")
p
好吧,現在我們有了傳說,但這可能看起來不像預期的那樣。 顏色圖例有一條紅線和一條灰色背景,而填充圖則有一條紅線和一條藍線! 這是因為ggplot2
認識到"Line of Best Fit"
和"Confidence Interval"
不是同一個字符串,因此為兩者創造了不同的審美價值。 在任何情況下,您都需要指定正確的color
和fill
值。
指定顏色:如果您在geom_smooth()
指定fill=
和color=
,它將覆蓋我們在aes()
中geom_smooth()
color=
,您將刪除圖例。 因此,我們將使用scale_color_manual()
和scale_fill_manual()
指定值。 我們也不想要圖例的標題,因此也可以將其刪除。
更改關鍵字形的外觀:您還想更改圖例的外觀。 對於“最佳擬合線”,您希望從該圖例圖標(稱為“關鍵字形”)中刪除填充。 對於“置信區間”,我們要刪除該行並僅顯示灰色框。 我們可以使用guides()
和guide_legend()
的override.aes=
參數來完成所有這些。
圖例的位置:最后,我們希望將圖例移到底部以獲得更好的整體外觀,可通過theme()
的legend.position=
元素訪問。 如果您想讓它們保持在右側,您可能需要修改legend.spacing
和legend.margin
的theme()
元素,使它們更接近一些。
將所有這些放在一起,我們得到以下內容:
p +
scale_fill_manual(NULL, values = 'gray') +
scale_color_manual(NULL, values = 'red') +
guides(
color=guide_legend(override.aes = list(fill=NA), order=1),
fill=guide_legend(override.aes = list(color=NA), order=2)
)+
theme(legend.position = "bottom")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.