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

ggplot2中geom_col绘图图例不显示问题求助

解决ggplot2中geom_col图例不显示的问题

你遇到的问题核心在于填充色没有和数据变量建立映射关系——你直接给geom_col的fill参数传了固定颜色向量,这让ggplot认为所有柱子都是同一类别,自然不会生成图例。要让图例显示,得把填充色的映射放到aes()里,再用手动颜色标度来指定你想要的颜色。

具体修改步骤:

  1. 将fill从geom_col的外部参数移到ggplot()的aes()中,绑定到variable变量(也就是你的state/site分类)
  2. 使用scale_fill_manual()来定义你想要的填充色,颜色数量对应variable的水平数(这里是2个,所以不需要4个颜色)
  3. 可以通过labs()的fill参数设置图例标题

修改后的完整代码:

library(ggplot2)
library(reshape2) # 用于melt函数

site <- c(0.700, 0.854)
site <- lapply(site, function(x) round((x*100),1))
site <- unlist(site, use.names=FALSE)
state <- c(0.726, 0.808)
state <- lapply(state, function(x) round((x*100),1))
state <- unlist(state, use.names=FALSE)
measure <- c("Individual", "Coalition")
measure <- unlist(measure, use.names=FALSE)
df1 <- data.frame(site,state,measure)
df2 <- melt(df1, id.vars='measure')
df2$variable <- factor(df2$variable, levels = c('state','site'),ordered = TRUE)

# 简化颜色向量,只需要对应variable的两个水平
fillcolors <- c("#7189A6", "#817BB0") 

myplot <- ggplot(df2, aes(measure, value, group = variable, fill = variable)) + 
  geom_col(width=.75, position=position_dodge(width=0.80)) + 
  labs(title = "Knowledge & Skills Gained", 
       x = "", 
       y = "", 
       fill="Level") + # 设置图例标题
  scale_y_continuous(limits=c(0,100), labels = function(x){ paste0(x, "%") }) + 
  scale_fill_manual(values = fillcolors) + # 手动指定填充色
  coord_flip() + 
  geom_text(aes(label=(paste0(value,"%"))), 
            size=3, 
            colour = "#57585a", 
            position=position_dodge(width=0.75), 
            vjust=.3, 
            hjust=-.1) + 
  theme(legend.position="right", 
        title = element_text(colour = "#57585a"), 
        legend.text = element_text(colour="#57585a", size = 9))
myplot

为什么这样修改有效?

  • 当fill被放到aes()中时,ggplot会识别到这是一个和数据变量关联的视觉属性,因此会自动生成对应的图例
  • scale_fill_manual()允许你自定义每个变量水平对应的颜色,同时保留图例的映射关系
  • 之前的4个颜色是多余的,因为variable只有两个水平(state和site),每个水平对应所有measure下的柱子,所以两个颜色就足够区分

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:34:33