You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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
Turkiye19905
Turkiye199145
Turkiye199350
US199080
US199185
US199384

需求与错误尝试

希望选择特定国家(如土耳其、瑞典)绘制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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 08:20:26