如何使用R语言ggplot2绘制是/否答案数量的堆叠条形图?
Stacked Bar Chart for Yes/No Answer Counts with ggplot2
Got it, here's a complete, human-friendly implementation to create a stacked bar chart for yes/no response counts using ggplot2 in R—including fixing the cut-off geom_text part from your original code and adapting it to your yes/no use case:
Step 1: Prepare Your Data
First, let's set up a dataset tailored to yes/no responses (you can swap in your actual year/response data):
# Load the ggplot2 package library(ggplot2) # Sample data (replace with your actual data) Year <- rep(c("2006-07", "2007-08", "2008-09", "2009-10"), each = 2) Response <- rep(c("Yes", "No"), times = 4) Frequency <- c(168, 259, 216, 431, 423, 645, 166, 467) # Convert to a data frame Data <- data.frame(Year, Response, Frequency)
Step 2: Build the Stacked Bar Chart
This code creates the stacked bars and adds centered labels to each segment for clarity:
ggplot(Data, aes(x = Year, y = Frequency, fill = Response, label = Frequency)) + # Create stacked bars using your pre-calculated frequencies geom_bar(stat = "identity") + # Add labels centered inside each bar segment geom_text(position = position_stack(vjust = 0.5), color = "white", fontface = "bold") + # Customize plot labels for readability labs( title = "Yes/No Response Counts by Year", x = "Academic Year", y = "Number of Responses", fill = "Response" ) + # Use a clean theme and center the title theme_minimal() + theme(plot.title = element_text(hjust = 0.5, size = 14, face = "bold"))
Quick Tips for Your Data:
- If you have raw individual responses (not pre-summarized frequencies), skip the
Frequencycolumn and usestat = "count"instead:# Example raw data (each row = one response) RawData <- data.frame( Year = sample(c("2006-07", "2007-08"), 500, replace = TRUE), Response = sample(c("Yes", "No"), 500, replace = TRUE) ) # Plot directly from raw data ggplot(RawData, aes(x = Year, fill = Response)) + geom_bar(position = "stack") + geom_text(stat = "count", aes(label = after_stat(count)), position = position_stack(vjust = 0.5), color = "white") - Adjust the
fillaesthetic to match your yes/no column name if it's not labeled "Response".
内容的提问来源于stack exchange,提问作者Konstancs
相关产品推荐
相关产品推荐

