You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

在R中自定义分组柱状图颜色时添加代码报错问题

Fixing the scale_fill_manual Error in Your ggplot Code

The error you're encountering is almost certainly caused by the smart curly quotes ( and ) used around your color values—R doesn’t recognize these as valid string delimiters, which breaks the code parsing.

Here’s the corrected version of your code with standard straight quotes:

ggplot(sex_excercise_genhlth, aes(genhlth, prop_exer, fill=sex)) + 
  geom_bar(stat="identity", colour="black", position="dodge" ) + 
  labs(title="Proportions of males to females who exercised in last 30 days compared to their general health", 
       x="General Health", 
       y="Proportion Exercise") +
  scale_fill_manual(values=c("blue", "pink"))

Extra Tip: Guarantee Exact Color-Gender Mapping

If you want to ensure colors are assigned to the correct gender (instead of relying on the default order of your sex variable), you can explicitly map each level to a color by name:

# First check the order of your sex levels with this command:
levels(sex_excercise_genhlth$sex)

# Then assign colors directly to each level (adjust names to match your data):
scale_fill_manual(values=c("Male" = "blue", "Female" = "pink"))

This ensures colors stay linked to the right gender even if the order of levels in your dataset changes later.

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

火山引擎 最新活动