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

使用ggplot制作堆叠柱状图:按列标签展示列总和并按行标签填充

Got it, let's fix this step by step! The key issue here is that your data is in wide format, but ggplot works best with long (tidy) data. Plus, we need to map the right variables to the aesthetic parameters correctly to get that stacked bar chart you want.

Step 1: Prep the Data (Convert to Long Format)

First, we'll turn your wide dataframe into a tidy format where each row represents a single observation (a group's value for one column). We'll also convert the row names into a proper column since ggplot can't directly use row names as an aesthetic variable.

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

# Convert row names to a column and pivot to long format
example_df_tidy <- example_df %>%
  tibble::rownames_to_column(var = "group") %>%
  pivot_longer(
    cols = starts_with("X"),  # Target all columns starting with X
    names_to = "column_name", # Name for the new column holding X1/X2/etc.
    values_to = "value"       # Name for the new column holding the numeric values
  )

Step 2: Build the Stacked Bar Chart with Correct Aesthetics

Now we can map the variables to ggplot's aesthetics properly:

  • x = column_name: Sets the X-axis to your column names (X1 to X15)
  • y = value: Uses the numeric values for the height of each stacked segment
  • fill = group: Colors each stacked segment by group (group1 to group6), creating the stacked effect
ggplot(example_df_tidy, aes(x = column_name, y = value, fill = group)) +
  geom_col() + # `geom_col` defaults to stacking, no need to specify position="stack" explicitly
  labs(
    title = "Stacked Bar Chart: Column Totals by Group",
    x = "Column Name",
    y = "Total Value",
    fill = "Group"
  ) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) # Tilt X-axis labels to avoid overlap

Quick Breakdown of the Aesthetics

  • x: Defines the categorical groups for each bar (your X1-X15 columns)
  • y: Defines the numeric values that make up each bar's height
  • fill: Defines which variable to use for coloring the stacked segments (your group1-group6 rows)

This setup will automatically stack each group's value within its corresponding column bar, and the total height of each bar will be the sum of all groups for that column—exactly what you're looking for!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 19:03:14