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

求助:如何使用ggplot2复现指定双柱状图?

使用ggplot2复现双柱状图的解决方案

目标图表说明

目标为分组双柱状图:每个地区对应两根柱子,左侧柱子代表icv指标,右侧柱子代表afl指标;所有地区按icv数值从高到低排序,柱子使用指定配色,同时柱子上方显示对应数值。

完整代码实现

library(tibble)
library(ggplot2)
library(dplyr)

# 定义配色
vectorcolors <- c("#967D2D", "#333333", "white")

# 数据集
df <- tibble(
  reg = c("Duarte","La Vega","Santiago","Hermanas Mirabal",
          "Sanchez Ramírez","María Trinidad Sánchez","Monseñor Nouel",
          "Puerto Plata","Samaná","Espaillat","Valverde",
          "Santiago Rodríguez","Dajabón","Montecristi"), 
  icv = c(69.9, 58.8, 57.1, 54.7, 53.9, 53.3, 49.3,
          48.8, 47.0, 45.4, 44.2, 43.2, 42.8, 42.5),
  afl = c(799.3, 800.6, 851.1, 711.7, 839.6, 710.9,
          823.2, 912.7, 605.8, 832.7, 692.0, 858.4,
          758.1, 616.6)
)

# 数据预处理:按icv降序排列地区,转换为因子保证绘图顺序
df_sorted <- df %>%
  arrange(desc(icv)) %>%
  mutate(reg = factor(reg, levels = reg))

# 转换为长格式,方便ggplot分组绘图
df_long <- df_sorted %>%
  pivot_longer(cols = c(icv, afl), names_to = "indicator", values_to = "value")

# 绘制图表
ggplot(df_long, aes(x = reg, y = value, fill = indicator)) +
  # 绘制分组柱状图,调整柱子间距
  geom_col(position = position_dodge(width = 0.8), width = 0.7) +
  # 添加柱子上方的数值标签
  geom_text(aes(label = round(value, 1)), 
            position = position_dodge(width = 0.8), 
            vjust = -0.3, size = 3.5) +
  # 设置指定配色
  scale_fill_manual(values = c(icv = vectorcolors[1], afl = vectorcolors[2])) +
  # 调整坐标轴标题和主题
  labs(x = "地区", y = "数值", fill = "指标") +
  theme_minimal() +
  theme(
    # 旋转x轴标签避免重叠
    axis.text.x = element_text(angle = 45, hjust = 1),
    # 设置图例位置
    legend.position = "top"
  )

关键代码解释

  • 数据排序:通过arrange(desc(icv))和factor(reg, levels = reg)确保地区按icv降序排列,绘图时不会打乱顺序。
  • 长格式转换:使用pivot_longer将宽格式数据转为长格式,是ggplot处理分组数据的标准方式。
  • 柱状图设置:position_dodge实现分组柱子并排,调整width参数控制柱子宽度和间距。
  • 数值标签:geom_text添加柱子上方的数值,vjust调整标签位置避免与柱子重叠。
  • 配色与主题:scale_fill_manual指定icv和afl对应的颜色,theme_minimal配合自定义主题优化视觉效果。

内容的提问来源于stack exchange,提问作者Fidel E. Morla M.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 04:36:17