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

如何使用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 Frequency column and use stat = "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 fill aesthetic to match your yes/no column name if it's not labeled "Response".

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:08:12