如何在R语言中为堆叠条形图按answer类别自定义颜色?解决‘Continuous value supplied to discrete scale’报错
Hey there! Let's break down what's going wrong and get your custom colors working for your stacked bar chart.
Why the Error Happens
Right now, your code maps fill = proportion in the aes() call. Since proportion is a continuous numerical value, ggplot treats the fill scale as continuous. But scale_fill_manual() is designed for discrete categorical variables—that's the mismatch causing the error. You want to color bars based on the answer categories, so we need to adjust what we map to the fill aesthetic.
Step-by-Step Fix
Map fill to
answerinstead ofproportion
Update your initial ggplot call to useansweras the fill variable, since that's the categorical group you want to color-code.Ensure
answeris a factor (optional but recommended)
If youranswercolumn is stored as a number, convert it to a factor so ggplot recognizes it as discrete categories:sample1$answer <- factor(sample1$answer)Add your custom color scale correctly
Nowscale_fill_manual()will work because it's targeting a discrete variable. The color values will correspond to each level ofanswer(1 through 5) in order.
Full Modified Code
# Convert answer to factor (if not already) sample1$answer <- factor(sample1$answer) # Build the plot p <- ggplot(sample1, aes(y = proportion, x = group, fill = answer)) + geom_bar(position = "stack", stat = "identity") + theme_minimal() + # Add your custom color scale here scale_fill_manual(values = c("#E7344E", "#0097BF", "#E7344E", "#0097BF", "#E7344E")) # Customize labels and theme with ggpar p1 <- ggpar(p, xlab = F, ylab = F, legend = "", ticks = F) # Add text labels p1 + geom_text(aes(label = proportion), position = position_stack(vjust = 0.5), check_overlap = T, colour = "white")
What This Does
- The fill aesthetic now ties directly to each
answercategory, so your custom colors will apply to each of the 5 answer types as intended. - The error disappears because we're no longer trying to use a discrete color scale on a continuous variable.
内容的提问来源于stack exchange,提问作者Vojtech Petr

