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

在ggplot2多分组折线图中添加整体增长率折线及图例

解决方案

要添加代表五个国家整体人口增长率的折线,你需要先计算每年总人口的占比,再将这部分数据合并到原有数据集,最后在绘图时纳入该类别。以下是修改后的完整代码:

数据处理部分

library(tidyr)
library(dplyr)
library(ggplot2)

data("population")

# 过滤目标国家和年份范围
filtered_df <- population %>% 
  filter(between(year, 2000, 2010) & country %in% c("Argentina", "Brazil", "Mexico", "Spain", "United States of America"))

# 计算单个国家的年度人口占比(与原逻辑一致)
country_pct <- filtered_df %>%
  group_by(country) %>%
  mutate(pct = 100 * population / sum(population)) %>%
  ungroup()

# 计算整体人口的年度占比
general_pct <- filtered_df %>%
  group_by(year) %>%
  summarise(total_pop = sum(population)) %>%  # 每年五个国家的总人口
  ungroup() %>%
  mutate(
    country = "General growth rate",  # 设置图例显示名称
    pct = 100 * total_pop / sum(total_pop)  # 计算整体占比
  ) %>%
  select(year, country, pct)  # 匹配原有数据的列结构

# 合并单个国家数据与整体数据
df <- bind_rows(country_pct, general_pct)

绘图部分

df %>% ggplot(aes(x = year, y = pct, col = country)) +
  scale_y_continuous(labels = function(x) paste0(x, "%"), 
                     limits = c(8.25, 9.75)) +
  scale_x_continuous(breaks = seq(2000, 2010, by = 1)) +
  geom_line(size = 2, linetype = "solid") +
  # 单独给整体增长率折线设置虚线样式,突出显示
  geom_line(data = filter(df, country == "General growth rate"), 
            linetype = "dashed", size = 2) +
  theme(legend.title = element_blank()) +
  labs(title = "Population growth rate",  
       subtitle = "2000-2010",
       x = "Year",
       y = "Percentage")

代码说明

  • 拆分单个国家与整体的计算逻辑,避免重复过滤数据;
  • 整体增长率的计算逻辑与单个国家一致:每年总人口占2000-2010年总人口总和的百分比;
  • 通过bind_rows合并数据后,ggplot会自动将"General growth rate"纳入图例;
  • 额外添加的geom_line给整体折线设置虚线样式,方便区分单个国家与整体趋势。

内容的提问来源于stack exchange,提问作者always.learning

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 03:25:01