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

如何用ggplot绘制《经济学人》风格哑铃图并标记下降区间

改成《经济学人》风格哑铃图的解决方案

没问题!我帮你把这段分组柱状图代码改成符合要求的哑铃图,还会给数值下降的部分加上粉色标记。咱们一步步来:

1. 准备所需工具包

除了你已经用到的ggplot2和ggthemes,我们还需要dplyr和tidyr来整理数据,方便对比两年的数值:

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

2. 数据预处理

先把原始的长格式数据转换成宽格式,让每个Reason对应的2018和2019数值在同一行,同时计算数值变化量、判断变化方向:

Animals <- read.table(
 header=TRUE,
 text='Year Reason Species
1 2018 Genuine 24
2 2019 Genuine 16
3 2019 Misclassified 85
4 2018 Misclassified 41
5 2018 Taxonomic 2
6 2019 Taxonomic 7
7 2018 Unclear 41
8 2019 Unclear 117')

# 转宽格式+计算变化方向
Animals_wide <- Animals %>%
  pivot_wider(names_from = Year, values_from = Species) %>%
  mutate(
    diff = `2019` - `2018`,
    direction = ifelse(diff < 0, "Decrease", "Increase")
  )

3. 绘制哑铃图

现在用ggplot2绘制哑铃图,结合theme_economist实现《经济学人》风格,同时给下降的部分(连线)设置粉色:

ggplot(Animals_wide, aes(y = Reason)) +
  # 绘制哑铃连接线,根据变化方向设置颜色
  geom_segment(
    aes(x = `2018`, xend = `2019`, yend = Reason, color = direction),
    size = 1.5
  ) +
  # 绘制2018年数值端点
  geom_point(aes(x = `2018`), size = 4, color = "#E24A33") +
  # 绘制2019年数值端点
  geom_point(aes(x = `2019`), size = 4, color = "#348ABD") +
  # 添加数值标签,让图表更直观
  geom_text(aes(x = `2018`, label = `2018`), hjust = -0.3, size = 3.5) +
  geom_text(aes(x = `2019`, label = `2019`), hjust = 1.3, size = 3.5) +
  # 自定义颜色:下降用粉色,上升用深灰
  scale_color_manual(values = c("Decrease" = "#FF9AA2", "Increase" = "#333333")) +
  # 应用《经济学人》主题
  theme_economist() +
  # 翻转坐标轴,让分类在y轴展示
  coord_flip() +
  # 设置图表标题和坐标轴标签
  labs(
    x = "Number of Species",
    y = "Reason",
    title = "Change in Species Count by Reason (2018 vs 2019)",
    color = "Change Direction"
  ) +
  # 调整细节,贴合《经济学人》风格
  theme(
    legend.position = "bottom",
    plot.title = element_text(size = 12, face = "bold")
  )

代码说明

  • geom_segment:负责绘制连接两年数值的“哑铃杆”,通过direction变量区分颜色,下降部分会显示你需要的粉色。
  • 两个geom_point:分别绘制2018和2019年的数值端点,用了《经济学人》常用的红蓝色系,你可以根据喜好调整。
  • geom_text:给每个端点添加数值标签,让读者能直接看到具体数值,不用额外猜测。
  • theme_economist():直接套用《经济学人》的字体、背景和配色逻辑,完美匹配你的风格需求。

运行这段代码后,你就能得到一张符合要求的哑铃图:数值下降的连线会显示粉色,整体风格和《经济学人》一致,还能清晰看到每个类别两年的数值变化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:50:50