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

求助:基于数值X轴的ggplot2堆叠条形图绘制及plotly转换报错

Fixing Your Stacked Bar Chart in ggplot2 (and Plotly)

Hey there! Let's get that stacked bar chart working properly. The core issue here is that your data is in wide format (each column is an X-axis category), but ggplot2 relies on long format data to create stacked visuals. Let's walk through the solution step by step.

Step 1: Understand Your Data Structure

First, let's recap your original data. You have:

one <- c(0.4, 0.3)
two <- c(0.4, 0.5)
df <- data.frame(one, two)
colnames(df) <- c("1", "2")

This creates a wide dataframe where each column represents an X-axis value ("1" and "2"), and each row represents a segment of the stacked bar. We need to add a label for these segments (so ggplot knows what to stack) and reshape the data.

Step 2: Reshape to Long Format

First, add a column to identify each stacked segment (we'll call these Group1 and Group2), then convert to long format using pivot_longer (the modern replacement for gather):

library(tidyverse)

# Add group labels for stacked segments
df$group <- paste0("Group", 1:nrow(df))

# Reshape to long format
df_long <- df %>%
  pivot_longer(
    cols = c("1", "2"),  # Columns to reshape
    names_to = "x_axis", # Name for the X-axis category column
    values_to = "value"  # Name for the numeric value column
  )

Your df_long will now look like this:

groupx_axisvalue
Group110.4
Group120.4
Group210.3
Group220.5

Step 3: Build the Stacked Bar Chart

Now we can use ggplot2 with the properly formatted data. We map x_axis to the X-axis, value to the Y-axis, and group to the fill color (which drives the stacking):

ggplot(df_long, aes(x = x_axis, y = value, fill = group)) +
  geom_bar(stat = "identity", position = "stack") + # stat="identity" uses our raw values
  labs(
    x = "X Axis",
    y = "Value",
    fill = "Stack Segment"
  ) +
  theme_minimal()

Step 4: Convert to Plotly (No Errors!)

Once you have a working ggplot, converting to Plotly is straightforward with ggplotly:

library(plotly)
ggplotly(last_plot())

Why Your Original Code Failed

  • Your initial ggplot(df,aes(df[,1:2])) tried passing raw column vectors to aes(), which ggplot can't interpret (hence the uneval class error). ggplot expects you to map column names to aesthetic attributes.
  • When you tried gather(), you likely didn't include the group column, so ggplot had no way to know how to split the bars into stacked segments.

That's it—you should now have a fully functional stacked bar chart that works in both ggplot2 and Plotly!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:34:16