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

如何在ggplot2中设置因子顺序和自定义颜色,解决scale_fill_manual打乱顺序问题

问题根源

你的代码执行顺序有误:预先创建my_scale时,还没有修改Behaviour列为自定义顺序的因子,此时颜色向量绑定的是原始数据默认的字母序分类水平,后续修改因子列顺序不会同步更新提前定义好的my_scale,就会出现顺序被覆盖的问题。
另外你给颜色向量命名的代码存在重复拼接的冗余逻辑,可直接简化。

修正后代码

# 优先调整Behaviour列为自定义顺序因子
behavssec$Behaviour <- factor(behavssec$Behaviour, levels = c(
  "Burst","High energy swimming", "Medium energy swimming", 
  "Low energy swimming", "Travel", "Ascending", "Descending"
))

# 再根据调整后的因子水平给自定义颜色命名
my_colors <- c("#1b9e77", "#d95f02", "#66A628", "#E81E89", "#7570b3", "#FFC000", "#0E85F2")
names(my_colors) <- levels(behavssec$Behaviour)
my_scale <- scale_fill_manual(name = "Behaviour", values = my_colors)

# 绘图
ggplot(behavssec, aes(fill=Behaviour, y=n, x= SharkID)) +
  geom_col(position = position_dodge2(width = 0.9, preserve = "single")) +
  theme_classic() + 
  my_scale +
  theme(
    axis.text.x = element_text(size = 12),
    axis.text.y = element_text(size = 16)
  ) +
  labs(x= "SharkID", y= "Time (second)")

运行后即可同时保留自定义因子顺序和自定义配色。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 17:24:03