[英]Add legend to ggplot2 graph when different x and y values are used for each line
我的問題與將圖例添加到ggplot2線圖非常相似,除了我遇到的情況是我有多種顏色-每個條件為1,但是它們並未繪制為通用的x軸值。 取而代之的是,我有2個x軸值,根據情況使用一個。
示例數據:
# dataframe name = df
e0 e200 o0 o50 o200
0.5715707 0.5755010 0.9151736 0.8858229 1.2488826
0.5570928 0.5610231 0.8724417 0.8851889 1.2135041
0.5430821 0.5470124 0.8692482 0.8793603 1.2051914
0.5295093 0.5334396 0.8251555 0.8636917 1.0951763
0.5163479 0.5202782 0.8149114 0.8519220 1.0787246
0.5035736 0.5075039 0.7875460 0.7521003 1.0655470
0.4911643 0.4950946 0.7724218 0.7394516 1.0616154
0.4790998 0.4830301 0.7306038 0.6997307 1.0214771
0.4673614 0.4712917 0.6373668 0.6333903 0.9179331
0.4559320 0.4598622 0.5898641 0.6314342 0.8713423
0.4447956 0.4487259 0.5870693 0.6266098 0.8208793
R腳本:
ggplot(df) +
geom_line(aes(x = e0,y = o0), size = 2, colour = "red") +
geom_line(aes(x = e0,y = o50), size = 2, colour = "orange") +
geom_line(aes(x = e200,y = o200), size = 2, colour = "gold") +
scale_colour_manual(name="Condition",
values=c("red", "orange", "gold"),
labels = c("0", "50", "200")) +
theme_classic()
如何在圖中添加圖例? 我嘗試將colour = "[colour]"
放在aes()
部分中,但隨后顏色在圖或圖例中無法正確匹配。
模棱兩可的列名很難確切地顯示出您想要的內容-但這是一種收集數據的方法。 如果您只是手動添加多行,則將來必須為每個新添加的“條件”重新編程,這是不好的做法。
library(ggplot2)
library(tidyr)
library(dplyr)
df_raw <- read.delim(
text = "e0 e200 o0 o50 o200
0.5715707 0.5755010 0.9151736 0.8858229 1.2488826
0.5570928 0.5610231 0.8724417 0.8851889 1.2135041
0.5430821 0.5470124 0.8692482 0.8793603 1.2051914
0.5295093 0.5334396 0.8251555 0.8636917 1.0951763
0.5163479 0.5202782 0.8149114 0.8519220 1.0787246
0.5035736 0.5075039 0.7875460 0.7521003 1.0655470
0.4911643 0.4950946 0.7724218 0.7394516 1.0616154
0.4790998 0.4830301 0.7306038 0.6997307 1.0214771
0.4673614 0.4712917 0.6373668 0.6333903 0.9179331
0.4559320 0.4598622 0.5898641 0.6314342 0.8713423
0.4447956 0.4487259 0.5870693 0.6266098 0.8208793",
sep = " ",
header = TRUE
)
df1 <- df_raw %>%
select(c(e0, o0, o50)) %>%
gather(o, y, o0:o50) %>%
mutate(e = "e0") %>%
rename(x = e0)
df2 <- df_raw %>%
select(c(e200, o200)) %>%
rename(x = e200, y = o200) %>%
mutate(e = "e200", o = "o200")
bind_rows(df1, df2) %>%
ggplot(aes(x, y, color = o)) +
geom_line(size = 2) +
scale_colour_manual(name="Condition",
values=c(o0 = "red", o50 = "orange", o200 = "gold"),
breaks = c("o0", "o50", "o200"))+
theme_classic()
您可以更進一步,使色階連續,這樣“ o25”將是較淺的橙色,依此類推。
您可以在aes
內部為每個geom_line
圖層使用colour
參數,並在scale_colour_manual
內部使用命名矢量,以正確地將geom_line
圖層映射到scale_colour_manual
如下所示:
ggplot(df) +
geom_line(aes(x = e0, y = o0, colour = "0"), size = 2) +
geom_line(aes(x = e0, y = o50, colour = "50"), size = 2) +
geom_line(aes(x = e200, y = o200, colour = "200"), size = 2) +
scale_colour_manual(name = "Condition",
values = c("0" = "red", "50" = "orange", "200" = "gold"),
breaks = c("0", "50", "200"),
guide = "legend") +
theme_classic()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.