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

关于条形图自定义颜色(无图例)及数据归并为‘其他’的技术咨询

一、条形图颜色设置解决方案

你用col参数没效果是因为ggplot中col控制的是图形边框颜色,条形图的填充色由fill参数控制,且你之前的颜色参数放置位置有误。要实现自定义填充色且不显示图例,有两种可行方法:

方法1:映射fill后手动指定颜色+隐藏图例

这种方法适合需要基于类别映射颜色的场景,之后通过主题设置隐藏图例:

ggplot(group.emission, aes(x = reorder(Emission_class, -emission_median), y = emission_median, fill = Emission_class)) +
  geom_bar(stat = "identity") +
  # 自定义颜色,顺序需与reorder排序后的Emission_class类别对应
  scale_fill_manual(values = c("lightgreen", "blue", "red", "yellow")) +
  labs(title = "Four main vehicle clusters, by carbon emission",
       y = "Carbon emision (median)", 
       x = "clusters") +
  # 隐藏图例
  theme(legend.position = "none")

方法2:直接在geom_bar中指定颜色(无需映射)

如果类别顺序固定,可直接在geom_bar里设置fill为颜色向量,这样不会生成图例:

ggplot(group.emission, aes(x = reorder(Emission_class, -emission_median), y = emission_median)) +
  geom_bar(stat = "identity", fill = c("lightgreen", "blue", "red", "yellow")) +
  labs(title = "Four main vehicle clusters, by carbon emission",
       y = "Carbon emision (median)", 
       x = "clusters")
二、数据归并(保留前10个Brand,其余归为“其他”)解决方案

使用forcats包的fct_lump_n()函数可快速实现需求,该函数会保留指定数量的高频类别,将剩余类别合并为自定义名称:

library(forcats)

# 按频率排序Brand,保留前10个,其余归为“其他”
electrical$Brand <- electrical$Brand %>%
  fct_infreq() %>%
  fct_lump_n(n = 10, other_level = "其他")

ncolor <- length(unique(electrical$Brand))
fcolors <- colorRampPalette(c("dark blue", "white"))

plot(electrical$Brand, las=2, ylim=c(0,30), cex.axis=0.5, cex=0.5, col=fcolors(ncolor))

注:fct_lump_n()默认保留频率最高的n个类别,若需按其他规则(如字母顺序)保留,需先调整排序逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 23:31:03