如何在R的ggplot中为各国GDP折线图添加最小值与最大值
在ggplot折线图中添加GDP最小值与最大值标记
以下是两种常见需求的实现方法,基于长格式的GDP数据(包含country、year、gdp三列):
1. 标记每个国家的GDP最值点
先从数据中筛选出每个国家GDP的最大值和最小值对应的记录,再将这些点和标签添加到折线图中:
library(ggplot2) library(dplyr) # 模拟示例数据(替换成你的真实数据) set.seed(123) gdp_data <- expand.grid(country = c("USA", "China", "Japan", "Germany"), year = 2000:2020) %>% mutate(gdp = case_when( country == "USA" ~ 10000 + 500*year - 0.1*year^2 + rnorm(n(), 0, 300), country == "China" ~ 2000 + 800*year - 0.05*year^2 + rnorm(n(), 0, 400), country == "Japan" ~ 8000 + 300*year - 0.15*year^2 + rnorm(n(), 0, 250), country == "Germany" ~ 7000 + 400*year - 0.12*year^2 + rnorm(n(), 0, 280) )) # 筛选每个国家的GDP最值行 gdp_country_extremes <- gdp_data %>% group_by(country) %>% filter(gdp == max(gdp) | gdp == min(gdp)) %>% ungroup() # 绘制带最值标记的折线图 ggplot(gdp_data, aes(x = year, y = gdp, color = country)) + geom_line(linewidth = 1) + # 添加最值点,用不同形状区分最大值/最小值 geom_point(data = gdp_country_extremes, aes(shape = ifelse(gdp == max(gdp), "最大值", "最小值")), size = 3, stroke = 1) + # 添加GDP数值标签 geom_text(data = gdp_country_extremes, aes(label = round(gdp, 0)), vjust = -1, hjust = 0.5, size = 3) + # 自定义形状样式 scale_shape_manual(values = c("最大值" = 19, "最小值" = 17)) + labs(title = "各国GDP年度趋势", x = "年份", y = "GDP", color = "国家", shape = "极值类型") + theme_minimal()
2. 标记全局GDP最值点
如果需要标记整个数据集里的GDP最大值和最小值(不区分国家),可以这样处理:
# 筛选全局GDP最值行 gdp_global_extremes <- gdp_data %>% filter(gdp == max(gdp) | gdp == min(gdp)) # 绘制带全局最值标记的折线图 ggplot(gdp_data, aes(x = year, y = gdp, color = country)) + geom_line(linewidth = 1) + # 用带填充的点突出全局最值 geom_point(data = gdp_global_extremes, size = 4, shape = 21, fill = "white", stroke = 2) + # 添加带国家名称的标签 geom_text(data = gdp_global_extremes, aes(label = paste0(round(gdp, 0), "\n(", country, ")")), vjust = -1.5, size = 3.5) + labs(title = "各国GDP年度趋势(含全局最值)", x = "年份", y = "GDP", color = "国家") + theme_minimal()
注意事项
- 如果你的数据是宽格式(列是国家,行是年份),需要先转成长格式:
library(tidyr) # wide_data是你的宽格式数据 long_data <- wide_data %>% pivot_longer(cols = -year, names_to = "country", values_to = "gdp") - 若存在多个年份对应同一最值(比如某国GDP连续两年相同且为最值),可以根据需求用
slice_max()/slice_min()替代filter(),避免重复标记:gdp_country_extremes <- gdp_data %>% group_by(country) %>% slice_max(gdp, n = 1) %>% bind_rows(gdp_data %>% group_by(country) %>% slice_min(gdp, n = 1)) %>% ungroup()
内容的提问来源于stack exchange,提问作者Jickson Thomas
相关产品推荐
相关产品推荐

