如何使用ggplot绘制单个国家随时间变化的SupDem折线图?
绘制特定国家SupDem随时间变化的折线图解决方案

初始代码
ggplot(classen, aes(Year, SupDem))+ geom_line(stat = 'summary', fun = mean, aes(color = 'mean'), linetype = 1) + scale_color_manual(values = c('orange')) + theme_minimal(base_size = 5)
数据集
| 国家名称(Country Name) | 年份(Year) | SupDem |
|---|---|---|
| Turkiye | 1990 | 5 |
| Turkiye | 1991 | 45 |
| Turkiye | 1993 | 50 |
| US | 1990 | 80 |
| US | 1991 | 85 |
| US | 1993 | 84 |
需求与错误尝试
希望选择特定国家(如土耳其、瑞典)绘制SupDem随时间变化的折线图,尝试以下代码后结果不符合预期:
ggplot(classen, aes(x=Year, y=mean(SupDem), colour= "Turkey")) + geom_line(size=0.6) + scale_color_manual(values = c("orange")) + theme_minimal(base_size = 9)

正确实现方法
1. 筛选单个国家后绘图
先提取目标国家的数据,再传入ggplot:
library(dplyr) library(ggplot2) # 筛选土耳其数据 turkiye_data <- classen %>% filter(`国家名称(Country Name)` == "Turkiye") # 绘制折线图 ggplot(turkiye_data, aes(x = Year, y = SupDem)) + geom_line(color = "orange", size = 0.6) + labs(title = "土耳其SupDem随时间变化", x = "年份", y = "SupDem") + theme_minimal(base_size = 9)
2. 直接在ggplot内筛选
无需额外存储数据集,一步完成筛选与绘图:
ggplot(classen %>% filter(`国家名称(Country Name)` == "Turkiye"), aes(x = Year, y = SupDem)) + geom_line(color = "orange", size = 0.6) + labs(title = "土耳其SupDem随时间变化", x = "年份", y = "SupDem") + theme_minimal(base_size = 9)
3. 同时绘制多个特定国家
若需展示多个国家,通过%in%限定范围,将国家名称映射到颜色:
ggplot(classen %>% filter(`国家名称(Country Name)` %in% c("Turkiye", "Sweden")), aes(x = Year, y = SupDem, color = `国家名称(Country Name)`)) + geom_line(size = 0.6) + scale_color_manual(values = c("Turkiye" = "orange", "Sweden" = "blue")) + labs(title = "多国家SupDem随时间变化", x = "年份", y = "SupDem", color = "国家") + theme_minimal(base_size = 9)
关键提示
- 必须先筛选数据,确保仅包含目标国家的记录,否则会用全量数据集计算导致结果错误。
- 你的数据中每个国家每年仅有一个SupDem值,无需用
mean(),直接映射SupDem即可;若同一国家同一年有多个数据点,可使用stat='summary', fun=mean计算平均值。
内容的提问来源于stack exchange,提问作者user19562955
相关产品推荐
相关产品推荐

