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

如何基于种子编号绘制多列数据的分组并列条形图?

实现并列条形图的方法

首先,你的数据可以用以下方式加载到R中:

df <- structure(list(seed_num = c(1, 2, 3, 4, 5), overall_dots = c(49L, 
49L, 49L, 49L, 49L), Lower_right = c(34L, 24L, 15L, 24L, 19L), 
    SP = c(14L, 11L, 4L, 9L, 8L), SC = c(4L, 4L, 5L, 5L, 5L)), class = "data.frame", row.names = c(NA, 
-5L))

要实现每个seed_num对应4个并列条形图,核心是把宽格式数据转成长格式,下面提供两种常用实现方法:

方法一:使用ggplot2(推荐)

ggplot2是R中最常用的绘图包,先安装并加载相关工具包:

# 首次使用时安装包
install.packages(c("ggplot2", "tidyr"))

# 加载包
library(ggplot2)
library(tidyr)

1. 转换数据格式

将除seed_num外的列转换为类别+数值的长格式:

df_long <- pivot_longer(df, cols = -seed_num, names_to = "category", values_to = "value")

2. 绘制并列条形图

ggplot(df_long, aes(x = factor(seed_num), y = value, fill = category)) +
  geom_bar(stat = "identity", position = position_dodge(width = 0.8), width = 0.7) +
  labs(
    x = "种子编号",
    y = "数值",
    title = "各种子编号对应指标条形图",
    fill = "指标类别"
  ) +
  theme_bw() +
  scale_fill_brewer(palette = "Set2") # 可选:设置配色方案
  • position_dodge(width = 0.8):控制并列条形的间距
  • width = 0.7:控制单个条形的宽度
  • 可根据需求调整标题、配色、主题等参数。

方法二:使用Base R绘图

如果不想加载额外包,也可以用Base R原生实现:

# 设置条形宽度和配色
bar_width <- 0.2
bar_colors <- c("#1b9e77", "#d95f02", "#7570b3", "#e7298a")

# 绘制并列条形图
x_positions <- barplot(
  t(df[, -1]),
  beside = TRUE,
  width = bar_width,
  col = bar_colors,
  xlab = "种子编号",
  ylab = "数值",
  main = "各种子编号对应指标条形图",
  names.arg = df$seed_num
)

# 添加图例
legend("topright", 
       legend = colnames(df)[-1],
       fill = bar_colors,
       bty = "n")
  • beside = TRUE:开启并列条形模式
  • t(df[, -1]):转置数据,适配Base R barplot的默认绘制逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 04:35:19