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

如何在R语言中为堆叠条形图按answer类别自定义颜色?解决‘Continuous value supplied to discrete scale’报错

Fixing the "Continuous value supplied to discrete scale" Error in Stacked Bar Chart

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

  1. Map fill to answer instead of proportion
    Update your initial ggplot call to use answer as the fill variable, since that's the categorical group you want to color-code.

  2. Ensure answer is a factor (optional but recommended)
    If your answer column is stored as a number, convert it to a factor so ggplot recognizes it as discrete categories:

    sample1$answer <- factor(sample1$answer)
    
  3. Add your custom color scale correctly
    Now scale_fill_manual() will work because it's targeting a discrete variable. The color values will correspond to each level of answer (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 answer category, 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 16:42:47