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

如何在R中使用ggplot()绘制符合需求的堆叠柱状图?

Fixing Your Stacked Bar Chart in ggplot2

Hey there! Let's get that stacked bar chart working for you. The issue with your original code is twofold: you're calling geom_bar() multiple times (which doesn't work for stacking), and ggplot2 relies on tidy (long-format) data for this type of plot—your current dataset is probably in wide format (with separate columns for Absent and Present). Here's a step-by-step solution:

1. Convert Your Data to Long Format

First, we'll reshape your wide data into long format using the pivot_longer() function from the tidyr package. This creates a single column for attendance status (Absent/Present) and another for the corresponding counts.

# Load required packages
library(ggplot2)
library(tidyr)

# Example wide-format data (replace with your actual data)
out <- data.frame(
  Session = c("S1", "S2", "S3"),
  Absent = c(5, 3, 7),
  Present = c(15, 17, 13)
)

# Reshape to long format
out_long <- out %>%
  pivot_longer(
    cols = c(Absent, Present),  # Columns to reshape
    names_to = "Attendance_Status",  # Name of the new category column
    values_to = "Count"  # Name of the new value column
  )

2. Create the Stacked Bar Chart

Now we can use the long-format data to build the stacked bar chart. The key is to map x to Session, y to Count, and fill to your attendance status column. We use stat = "identity" because we're using pre-calculated counts (not letting ggplot count observations automatically).

# Build the plot
p <- ggplot(out_long, aes(x = Session, y = Count, fill = Attendance_Status)) +
  geom_bar(stat = "identity") +  # Use identity since we have raw counts
  # Add labels for clarity
  labs(
    title = "Attendance by Session",
    x = "Session",
    y = "Number of Participants",
    fill = "Status"
  ) +
  # Optional: Use a clean theme
  theme_minimal()

# Display the plot
print(p)

Why Your Original Code Failed

  • Multiple geom_bar() calls don't stack values—they just layer bars on top of each other, which leads to incorrect visualization.
  • You didn't map the y axis to your count values, and the fill aesthetic wasn't properly linked to the two attendance categories.
  • Without stat = "identity", geom_bar() defaults to counting rows, which isn't what you want when you have pre-defined counts in Absent and Present.

If your data is already in long format, you can skip the pivot_longer() step and jump straight to the ggplot code!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:23:14