簡體   English   中英

使用 ggplot2 (r) 向具有兩個數據框的繪圖添加圖例

[英]Adding a legend to a plot with two data frames using ggplot2 (r)

我試圖在體育課上繪制男孩和女孩每分鍾的平均心率,看看是否存在一些性別差異。 我想使用 ggplot2 以兩種不同的顏色表示性別來繪制 2 個折線圖 我的問題是,我正在使用兩個不同的數據框,並且無法添加顯示“綠色 = 男孩,紅色 = 女孩”的圖例

這是我的數據框:wDaten2809HR 和 mDaten2809HR。

這是我的情節的當前代碼,沒有顯示任何圖例:

ggplot(NULL, aes(x= minute, y= meanHR))+
  geom_line(data= wDaten2809HR, color= "orangered2", size= 0.7)+
  geom_line(data= mDaten2809HR, color= "seagreen3", size= 0.7)+
  scale_x_continuous(expand= c(0, 0), limits = c(0,35), breaks= c
                     (0, 5, 10, 15, 20, 25, 30, 35), name= "Zeit [min]")+
  scale_y_continuous(breaks = c(70, 90, 110, 130, 150, 170, 190, 210), limits= c(70, 210), name = "Herzrate [BPM]")+
  theme_grey()+
  labs(title = "Geschlechtervergleich - durchschnittliche Herzrate",
       subtitle = "28.09.2021")+
  theme(plot.title = element_text(size = 12, color = "black", hjust = 0.5),
        plot.subtitle = element_text(size = 10, color = "grey50", hjust = 0.5), legend.position = "bottom")

我可以看到該圖顯示了兩個圖表,但由於兩個數據框而沒有圖例。 我嘗試了很多不同的東西,這些東西在編碼網站上解釋過手動添加圖例,但我迷路了,沒有任何效果。 有人可以幫忙嗎?

我認為如果您首先進行一些數據操作以組合兩個數據框,那么這是最簡單的。 在這種情況下,您可以使用mutate() 然后您可以指定線條的顏色應該代表gender列。

library(tidyverse)

df_boys <- data.frame(
  time = c(1:10),
  heart_rate = c(100:109)
)
df_girls <- data.frame(
  time = c(1:10),
  heart_rate = c(105:114)
)

df <- bind_rows(
  df_boys %>% mutate(gender = "M"),
  df_girls %>% mutate(gender="F")
)


ggplot(df, aes(x=time, y=heart_rate, group=gender)) + 
  geom_line(aes(colour=gender))

reprex 包(v2.0.1) 創建於 2022-05-16

該解決方案旨在手動創建geom_line()aes()內的圖例指定圖例 id,然后在scale_colour_manual()中引用它們

ggplot(NULL, aes(x= minute, y= meanHR))+
  geom_line(data= wDaten2809HR, 
            aes(color = "woman"),
            size= 0.7)+
  geom_line(data= mDaten2809HR, 
            aes(color = "man"),
            size= 0.7)+
  scale_x_continuous(expand= c(0, 0), 
                     limits = c(0,35), 
                     breaks= c(0, 5, 10, 15, 20, 25, 30, 35), name= "Zeit [min]")+
  scale_y_continuous(breaks = c(70, 90, 110, 130, 150, 170, 190, 210),
                     limits= c(70, 210),
                     name = "Herzrate [BPM]")+
  scale_color_manual(name='Legend name',
                     breaks=c('woman', 'man'),
                     values=c('woman'='orangered2', 
                              'man'='seagreen3')) +
  theme_grey()+
  labs(title = "Geschlechtervergleich - durchschnittliche Herzrate",
       subtitle = "28.09.2021")+
  theme(plot.title = element_text(size = 12,
                                  color = "black", 
                                  hjust = 0.5),
        plot.subtitle = element_text(size = 10, 
                                     color = "grey50", 
                                     hjust = 0.5), 
        legend.position = "bottom")

暫無
暫無

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

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