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

ggplot2绘图技术咨询:合并柱状类别并叠加折线图

解决方案:合并类别 + 混合柱状图与折线图

没问题,这两个需求都能轻松实现,我来一步步帮你搞定:

1. 合并confirmed和recovered为单个柱状条

要把这两个类别合并成一个柱子,核心是先对数据做预处理,将这两类合并为一个新类别后再汇总数值。用dplyr就能快速完成:

library(dplyr)
library(ggplot2)

# 预处理数据:合并confirmed和recovered为新类别
summary_df_combined <- summary_df_cont %>%
  mutate(
    # 创建新的类别列,把两类合并
    case_category = case_when(
      type %in% c("confirmed", "recovered") ~ "Confirmed + Recovered",
      TRUE ~ type  # 保留death类别不变
    )
  ) %>%
  # 按大洲和新类别分组求和
  group_by(continent, case_category) %>%
  summarise(total_cases = sum(total_cases), .groups = "drop")

之后用处理好的数据绘制柱状图,就能看到合并后的单个柱子了:

ggplot(summary_df_combined, aes(x = continent, y = total_cases, fill = case_category)) +
  geom_bar(stat = "identity")

2. 在同一图表中用geom_line()绘制death数据

要在柱状图上叠加折线图,只需要给geom_line()指定单独的数据源(过滤出death类别的数据),同时注意设置group=1让ggplot知道要把所有大洲的死亡数据连起来:

结合第一个需求的完整代码

ggplot() +
  # 绘制合并后的柱状条(Confirmed+Recovered)
  geom_bar(
    data = filter(summary_df_combined, case_category == "Confirmed + Recovered"),
    aes(x = continent, y = total_cases, fill = case_category),
    stat = "identity",
    width = 0.7  # 调整柱子宽度,避免和折线重叠
  ) +
  # 绘制death的折线图
  geom_line(
    data = filter(summary_df_cont, type == "death"),
    aes(x = continent, y = total_cases, group = 1, color = type),
    size = 1.2  # 调整折线粗细,让它更显眼
  ) +
  # 添加数据点让折线更清晰(可选)
  geom_point(
    data = filter(summary_df_cont, type == "death"),
    aes(x = continent, y = total_cases, color = type),
    size = 3
  ) +
  # 美化图表标签和样式
  labs(
    title = "COVID Cases by Continent",
    x = "Continent",
    y = "Total Cases",
    fill = "Aggregated Case Type",
    color = "Case Type"
  ) +
  theme_minimal()

关键说明

  • 用ggplot()空开头,然后分别添加geom_bar()和geom_line(),各自指定对应的数据源,避免数据冲突。
  • group=1是必须的:因为continent是离散型变量,ggplot需要明确知道这些折线点属于同一个系列,否则不会把它们连接起来。
  • 如果death的数值和合并后的柱状条数值差距很大,你可以考虑添加双y轴,但一般不推荐(会影响可读性),如果确实需要可以再调整。

内容的提问来源于stack exchange,提问作者Rajat Joshi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 08:48:13