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

如何在R语言中为给定数据集创建指定样式的条形图?

使用R语言绘制指定样式的条形图

数据集

state_utyearprimary_meanupper_primary_meansecondary_meanhrsecondary_mean
All India201397.5097.7398.1798.40
All India201497.9598.2798.5598.98
All India201598.2798.5798.8999.02

目标样式说明

从草图来看,需绘制分组条形图:以年份为X轴分组,每个年份下对应4个并排条形,分别代表小学、初中、高中、高等中学的均值,同时显示每个条形的数值标签,用图例区分不同教育阶段。

实现代码

使用tidyverse包(整合ggplot2绘图与dplyr数据处理)完成:

1. 安装并加载依赖包

# 首次运行需安装
install.packages("tidyverse")
# 加载包
library(tidyverse)

2. 创建数据集

df <- data.frame(
  state_ut = rep("All India", 3),
  year = c(2013, 2014, 2015),
  primary_mean = c(97.50, 97.95, 98.27),
  upper_primary_mean = c(97.73, 98.27, 98.57),
  secondary_mean = c(98.17, 98.55, 98.89),
  hrsecondary_mean = c(98.40, 98.98, 99.02)
)

3. 转换数据格式

将宽格式转为长格式,适配分组绘图需求:

df_long <- df %>%
  pivot_longer(
    cols = -c(state_ut, year),
    names_to = "education_stage",
    values_to = "mean_value"
  ) %>%
  # 重命名教育阶段,提升可读性
  mutate(
    education_stage = factor(
      education_stage,
      levels = c("primary_mean", "upper_primary_mean", "secondary_mean", "hrsecondary_mean"),
      labels = c("小学", "初中", "高中", "高等中学")
    )
  )

4. 绘制分组条形图

ggplot(df_long, aes(x = factor(year), y = mean_value, fill = education_stage)) +
  # 绘制并排条形
  geom_bar(stat = "identity", position = position_dodge(width = 0.8), width = 0.7) +
  # 添加条形顶部数值标签
  geom_text(
    aes(label = mean_value),
    position = position_dodge(width = 0.8),
    vjust = -0.5,
    size = 3.5
  ) +
  # 设置坐标轴与标题
  labs(
    x = "年份",
    y = "均值",
    title = "印度各教育阶段均值变化(2013-2015)",
    fill = "教育阶段"
  ) +
  # 设置简洁主题
  theme_minimal() +
  theme(
    plot.title = element_text(hjust = 0.5, size = 14, face = "bold"),
    axis.title = element_text(size = 12),
    legend.title = element_text(size = 12)
  )

自定义调整说明

  • 若需堆叠条形图,将position = position_dodge(width = 0.8)改为position = position_stack()即可。
  • 可通过scale_fill_manual(values = c("#颜色1", "#颜色2", ...))自定义条形颜色。
  • 数值标签的位置、大小可通过vjust、size参数调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 19:55:49