[英]How to create a linetype legend in ggplot with different dataframes
一段時間以來,我一直在努力在我的 ggplot 中創建一個圖例,但我找不到任何有效的答案。
這是我的 ggplot 的精簡版:
ggplot() +
geom_smooth(data = mydf1, aes(x, predicted, linetype = 1), method = "lm", linetype = 1, colour = "black") +
geom_smooth(data = mydf2, aes(x, predicted, linetype = 2), method = "lm", linetype = 2, colour = "black") +
geom_smooth(data = mydf3, aes(x, predicted, linetype = 3), method = "lm", linetype = 3, colour = "black") +
theme_classic()
如您所見,我從不同的數據幀(mydf1、mydf2、mydf3)中獲取數據。 現在我想手動添加一個圖例,指定實線是“第 1 組”,長虛線是“第 2 組”,虛線線型是“第 3 組”。 但是,無論我嘗試什么,我的 ggplot 中都沒有圖例出現。 我在 aes() 中包含了線型,嘗試了我能想到的關於 scale_linetype_manual() 的所有方法,並且我一直在四處尋找解決方案,但沒有出現任何圖例。
我錯過了一些明顯的東西嗎? 我只需要旁邊的一個小圖例說明不同線型的含義。
我的數據如下:
mydf1 <- data.frame(x = c(seq(-1,1, 0.2)),
predicted = c(-0.27066438, -0.23568714, -0.20070991, -0.16573267, -0.13075543, -0.09577819, -0.06080095, -0.02582371, 0.00915353, 0.04413077, 0.07910801))
mydf2 <- data.frame(x = c(seq(-1,1, 0.2)),
predicted = c(-0.39806988, -0.34348641, -0.28890295, -0.23431948, -0.17973602, -0.12515255, -0.07056909, -0.01598562, 0.03859784, 0.09318131, 0.14776477))
mydf3 <- data.frame(x = c(seq(-1,1, 0.2)),
predicted = c(-0.25520076, -0.22917917, -0.20315758, -0.17713600, -0.15111441, -0.12509282, -0.09907123, -0.07304964, -0.04702806, -0.02100647, 0.00501512))
盡管任何實用的解決方案都會有所幫助,但我並不一定希望將數據幀合並為一個並重做 ggplot。 謝謝!
將線線型引入 aes() 並使用 lab() 為圖例提供標題。
ggplot() +
geom_smooth(data = mydf1, aes(x, predicted, linetype = "Group 1"), method = "lm", colour = "black") +
geom_smooth(data = mydf2, aes(x, predicted, linetype = "Group 2"), method = "lm", colour = "black") +
geom_smooth(data = mydf3, aes(x, predicted, linetype = "Group 3"), method = "lm", colour = "black") +
labs(linetype="Group") +
theme_classic()
這是使用bind_rows
的另一種方法:
library(dplyr)
library(ggplot2)
bind_rows(mydf1, mydf2, mydf3) %>%
mutate(group = as.integer(gl(n(), 11, n()))) %>%
ggplot(aes(x, predicted, linetype=factor(group)))+
geom_smooth(color="black", method = "lm", se=F) +
scale_linetype_discrete(name="group",
breaks=c(1, 2, 3),
labels = c("group1", "group2", "group3"))+
theme_classic()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.