簡體   English   中英

如何使用ggplot在同一圖中繪制兩條平滑樣條線?

[英]How can I plot two smoothing splines in the same plot with ggplot?

例如,我有幾個這樣的情節:

ggplot(mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth(method = "lm", formula = y ~ splines::bs(x, 3), se = T)

是否可以將此類2繪制到同一圖中?

如果只想添加其他功能,請添加另一層: + geom_smooth()

情節1

ggplot(mpg, aes(displ, hwy)) + geom_point() + 
geom_smooth(method = "lm", formula = y ~ splines::bs(x, 3), se = T) +
geom_smooth(method = "lm", formula = y ~ splines::bs(x, 4), se = T)

如果要添加其他數據框中的數據,請在geom_smooth內添加df信息:

情節2

ggplot(mpg, aes(displ, hwy)) + geom_point() + 
geom_smooth(method = "lm", formula = y ~ splines::bs(x, 3), se = T) + 
geom_smooth(data = mpg, aes(x = displ, y = cyl), method = "lm", formula = y ~ splines::bs(x, 4), se = T)

最后,自定義顏色和圖例: color參數必須位於aes內部才能出現在圖例中

在此處輸入圖片說明

ggplot(mpg, aes(displ, hwy)) + geom_point() + 
geom_smooth(aes(color = "B"),method = "lm", formula = y ~ splines::bs(x, 3), se = T) + 
geom_smooth(data = mpg, aes(x = displ, y = cyl, color = "A"), method = "lm", formula = y ~ splines::bs(x, 4), se = T) + 
scale_color_manual("Legend Title", values = c("A" = "red", "B" = "blue"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM