我用 stat_summary() 函式創建了一個平均值,但我無法將它添加到圖例中。我想知道,是否可以這樣做?
這是我的代碼:
gap %>%
filter(country %in% c("Angola","Botswana","Lesotho","Malawi","Mozambique",
"Namibia","Swaziland","South Africa","Zambia","Zimbawe")) %>%
ggplot(aes(x=year,y=life_expectancy, col=country))
geom_line(size=1.2, alpha=0.7)
stat_summary(fun = mean,geom = "line", size= 1.5,col="black")
theme_light()
labs(title="Evolució de l'expectativa de vida en l’àfrica Austral",
x= "1960-2016",
y="Expectativa de vida",
col= "Llegenda",
tag = "Fig. 3")
幫助將不勝感激,謝謝!
我已經嘗試過教程,但我唯一取得的成就是洗掉了所有國家/地區的圖例,并且只出現了平均值的圖例,這不是我需要的。
uj5u.com熱心網友回復:
一種選擇是在美學上進行映射,即使用coloraesstat_summary并通過 設定您想要的顏色scale_color_manual。
使用gapminder::gapminder資料集作為示例資料:
library(ggplot2)
library(dplyr)
library(gapminder)
# example data
gap <- gapminder |>
rename(life_expectancy = lifeExp)
cntrys <- c(
"Angola", "Botswana", "Lesotho", "Malawi", "Mozambique",
"Namibia", "Swaziland", "South Africa", "Zambia", "Zimbawe"
)
pal_color <- c(scales::hue_pal()(length(cntrys)), "black")
names(pal_color) <- c(cntrys, "Mean life expectancy")
gap %>%
filter(country %in% cntrys) %>%
ggplot(aes(x = year, y = life_expectancy, col = country))
geom_line(size = 1.2, alpha = 0.7)
stat_summary(aes(color = "Mean life expectancy"), fun = mean, geom = "line", size = 1.5)
scale_color_manual(values = pal_color, breaks = names(pal_color))
theme_light()
labs(
title = "Evolució de l'expectativa de vida en l’àfrica Austral",
x = "1960-2016",
y = "Expectativa de vida",
col = "Llegenda",
tag = "Fig. 3"
)
#> Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
#> ? Please use `linewidth` instead.

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/537770.html
標籤:r图表2传奇意思是
