如何在R中使用ggplot()绘制符合需求的堆叠柱状图?
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
yaxis to your count values, and thefillaesthetic 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 inAbsentandPresent.
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

