使用ggplot2绘制堆叠条形图手动设色时遇报错及数据问题
Let's break down and fix both the error and warning you're seeing:
1. Fixing the "Continuous value supplied to discrete scale" Error
The root issue here is that your row variable is a continuous integer (created with seq_len()), but scale_fill_manual expects a discrete categorical variable to map colors to. ggplot gets confused when you try to feed a continuous value into a discrete fill scale.
Solution: Convert row to a Factor
When creating the row column, explicitly turn it into a factor instead of leaving it as an integer:
matrix$row <- as.factor(seq_len(nrow(matrix)))
This tells ggplot to treat each row as a distinct category, which plays nicely with your manual color scale.
2. Fixing the "Removed 83 rows containing missing values" Warning
This warning pops up because your melted data (dat2) includes rows where value=0. When using position="fill" (which stacks bars proportionally), these 0-value rows contribute nothing to the bar height, so ggplot automatically removes them to avoid empty "slots" in the stack.
Solution (Optional but Recommended): Filter Out 0-Value Rows
If you don't need to display 0s (which makes sense for proportional stacking), filter them out before plotting to eliminate the warning:
# Using dplyr (cleaner syntax) dat2 <- melt(matrix, id.vars = "row") %>% dplyr::filter(value != 0) # Or base R if you don't have dplyr installed dat2 <- dat2[dat2$value != 0, ]
Full Fixed Code
Putting it all together, here's the corrected code with a small typo fix in your color vector (missing hash for #00FFFF):
library(reshape2) library(ggplot2) # Create row as factor instead of integer matrix$row <- as.factor(seq_len(nrow(matrix))) # Melt data and filter out 0 values dat2 <- melt(matrix, id.vars = "row") %>% dplyr::filter(value != 0) # Your color vector (fixed hex color typo) fill_2 <- c("yellow2", "hotpink4" , "brown", "rosybrown2", "seagreen", "royalblue" , "#FFFFCC","#CCFF66", "#99CC00", "#CC9900", "#FF9933", "#CC6666", "#FF3333", "black", "royalblue1", "royalblue2", "royalblue3", "royalblue4", "navy", "chocolate1", "chocolate2", "chocolate3" , "chocolate4" , "brown1" , "brown2", "brown3", "brown4", "azure", "azure1", "azure2", "azure3", "#00FFFF", "#33FFCC", "#66FF99", "#99FFFF", "#CCFFFF", "#006666" ) # Plot with corrected fill variable ggplot(dat2, aes(y = value, x = variable, fill = row, group = row)) + geom_bar(stat = "identity", position = "fill") + guides(fill = FALSE) + scale_fill_manual(values = fill_2)
Quick Check:
Since your fill_2 vector has exactly 37 colors (matching your 37-row dataset), converting row to a factor ensures each row gets the unique color you intended.
内容的提问来源于stack exchange,提问作者sdabral

