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

如何用R语言的ggplot2绘制行数据的堆叠条形图

How to Create a Stacked Bar Chart with ggplot2 for Your Workload Data

Hey there! I totally get the confusion with ggplot2's parameters when you're just starting out—stacked bar charts do require getting your data in the right shape first, so let's break this down step by step with your exact data.

Step 1: Load Required Packages

We'll use the tidyverse package, which includes both ggplot2 (for plotting) and tidyr (for reshaping data):

library(tidyverse)

Step 2: Create Your Reproducible Data

First, let's turn your sample data into a usable R data frame:

workload_data <- data.frame(
  Workload = c("W1", "W2", "W3", "W4"),
  P1 = c(0.3, 0.5, 0.2, 0.3),
  P2 = c(0.2, 0.1, 0.3, 0.2),
  P3 = c(0.4, 0.3, 0.4, 0.5),
  P4 = c(0.1, 0.1, 0.1, 0.1)
)

Step 3: Reshape Data from Wide to Long Format

ggplot2 works best with tidy (long) data, where each row represents a single observation. Your current data is in wide format (one column per parameter), so we'll use pivot_longer() to reshape it:

long_data <- workload_data %>%
  pivot_longer(cols = starts_with("P"),  # Select all columns starting with "P"
               names_to = "Parameter",   # Name of the new column for parameter labels
               values_to = "Value")      # Name of the new column for parameter values

After this, your data will look like this (each row is a Workload + Parameter combination):

ParameterValue
P10.3
P20.2
P30.4
P40.1
......

Step 4: Build the Stacked Bar Chart

Now we can use ggplot() to create the stacked bar chart. We'll use geom_col() (instead of geom_bar()) because we're plotting pre-calculated values (not counts):

ggplot(long_data, aes(x = Workload, y = Value, fill = Parameter)) +
  geom_col() +  # Creates stacked bars since we're mapping fill to Parameter
  labs(
    title = "Stacked Parameter Values by Workload",
    x = "Workload",
    y = "Proportion",
    fill = "Parameter"  # Legend title
  ) +
  theme_minimal()  # Optional: Clean, minimal theme for better readability

Key Explanations:

  • aes(x = Workload, y = Value, fill = Parameter): Maps your Workload column to the x-axis, the numeric values to the y-axis, and uses the Parameter labels to color (fill) each segment of the bar.
  • geom_col(): Automatically stacks the bars because we're using fill to group the data—each Workload bar will be split into segments for P1-P4, with heights matching their values.
  • The labs() function lets you customize titles and labels to make your plot clearer.

If you want to adjust the order of the parameters in the stack, you can reorder the Parameter factor (e.g., long_data$Parameter <- factor(long_data$Parameter, levels = c("P4", "P3", "P2", "P1")) before plotting).

内容的提问来源于stack exchange,提问作者Chetan Arvind Patil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:09:06