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

在R中绘制带误差棒的分组条形图:特定数据集分组需求

Solution for Grouped Bar Plot with Error Bars in R

Hey there! Let's work through this grouped bar plot problem step by step—since you're learning R, I'll break down each part so you understand what's going on.

First, let's start with your data. From your output, dataplot is a 1-row matrix. We'll first restructure it into a format that's easier to work with for grouped bar plots:

# Reproduce your data (matching the output you shared)
dataplot <- matrix(c(0.9685, 0.0150831, 0.9253333, 0.03018388, 0.9856667, 0.01330664,
                     0.9268333, 0.05894885, 0.9686667, 0.01478738, 0.9313333, 0.07123389),
                   nrow = 1,
                   dimnames = list(NULL, c("a","b","c","d","e","f","g","h","i","j","k","l")))

# Extract mean values grouped as you requested:
# Group 1: a, c; Group 2: e, g; Group 3: i, k
mean_vals <- matrix(c(dataplot[,"a"], dataplot[,"c"],
                      dataplot[,"e"], dataplot[,"g"],
                      dataplot[,"i"], dataplot[,"k"]),
                    nrow = 3, byrow = TRUE,
                    dimnames = list(c("Group 1", "Group 2", "Group 3"), c("Type 1", "Type 2")))

# Extract corresponding standard deviations:
# Group 1: b (sd for a), d (sd for c)
# Group 2: f (sd for e), h (sd for g)
# Group 3: j (sd for i), l (sd for k)
sd_vals <- matrix(c(dataplot[,"b"], dataplot[,"d"],
                    dataplot[,"f"], dataplot[,"h"],
                    dataplot[,"j"], dataplot[,"l"]),
                  nrow = 3, byrow = TRUE,
                  dimnames = list(c("Group 1", "Group 2", "Group 3"), c("Type 1", "Type 2")))

Next, we'll create the grouped bar plot. The base R barplot() function works best with matrices for grouped data, so we'll adjust spacing and colors to match your requirements:

# Set bar width and spacing between groups
bar_width <- 0.35
group_spacing <- 0.2

# Create the bar plot and store the x positions of each bar (critical for error bars)
bar_pos <- barplot(t(mean_vals),
                   beside = TRUE,  # Places bars side-by-side for each group
                   width = bar_width,
                   space = c(0, group_spacing),  # No gap between bars in same group, gap between groups
                   col = c("#1f77b4", "#ff7f0e"),  # Colors for Type 1 (a/e/i) and Type 2 (c/g/k)
                   main = "Grouped Bar Plot with Error Bars",
                   xlab = "Groups",
                   ylab = "Mean Value",
                   ylim = c(0, max(mean_vals + sd_vals) * 1.1))  # Expand y-axis to fit error bars

# Add error bars using arrows()
for (i in 1:nrow(mean_vals)) {
  for (j in 1:ncol(mean_vals)) {
    # Grab the x position of the current bar
    x <- bar_pos[j, i]
    # Draw vertical error bar (up and down from the mean)
    arrows(x0 = x, y0 = mean_vals[i,j] - sd_vals[i,j],
           x1 = x, y1 = mean_vals[i,j] + sd_vals[i,j],
           length = 0.05, angle = 90, code = 3)
  }
}

# Add a legend to clarify bar colors
legend("topright",
       legend = c("a/e/i", "c/g/k"),
       fill = c("#1f77b4", "#ff7f0e"))

Key breakdown of the code:

  • Data Restructuring: We converted your flat 1-row matrix into two 3x2 matrices (one for means, one for SDs) organized by your groups. This makes it simple to map to grouped bars.
  • barplot() Settings:
    • beside = TRUE ensures bars in the same group sit side-by-side instead of stacked.
    • space controls spacing: c(0, group_spacing) removes gaps between paired bars but adds space between different groups for clarity.
    • ylim expands the y-axis just enough to prevent error bars from getting cut off.
  • Error Bars: The arrows() function draws vertical lines with small "caps" (via angle = 90 and code = 3). We loop through each mean/SD pair to place bars exactly on top of their corresponding bar.
  • Legend: Helps viewers quickly match bar colors to your column sets.

If you run this code, you'll get the exact grouped bar plot you requested: three groups, two colored bars per group, and error bars using the correct standard deviations.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:19:40