求助:基于数值X轴的ggplot2堆叠条形图绘制及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:
| group | x_axis | value |
|---|---|---|
| Group1 | 1 | 0.4 |
| Group1 | 2 | 0.4 |
| Group2 | 1 | 0.3 |
| Group2 | 2 | 0.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 toaes(), which ggplot can't interpret (hence theunevalclass error). ggplot expects you to map column names to aesthetic attributes. - When you tried
gather(), you likely didn't include thegroupcolumn, 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

