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

使用coord_polar()和facet_wrap()绘制饼图时图例出现字母a的解决咨询

解决ggplot分面饼图图例出现小写字母"a"的问题

问题原因

你在绘图时同时给fill和color两个美学属性绑定了uniconnex变量,ggplot会自动合并这两个属性的图例。其中color属性的默认图例符号是文本(显示为小写字母"a"),和fill的填充矩形叠加后,就出现了图例框里的"a"。此外代码中还有几处冗余设置:

  • 重复定义了8元素的uniconnex向量,但实际数据中该因子只有4个水平,导致标签重复;
  • 冗余的group参数(fill已能实现分组);
  • labs()中多余的shape设置(未映射该属性)。

解决方案

方案1:移除不必要的color映射

如果不需要饼图边框,直接删除color相关的映射和设置,代码更简洁:

ggplot(df.connexuniv.location, aes(x="", y=percentage, fill=uniconnex)) + 
  geom_bar(width=1, stat="identity")  +
  coord_polar("y", start=0, direction=-1) + facet_wrap(~location) +
  scale_fill_manual(
    values=c("grey20","grey60", "grey90","grey99"),
    name = "Connection to university", 
    labels=levels(df.connexuniv.location$uniconnex)
  ) +
  labs(x=" ", y="percentage of audience") +
  theme(
    panel.border = element_rect(linetype = "solid", colour="black", linewidth=.5, fill = NA), 
    panel.background=element_rect(fill="grey97"), 
    strip.background = element_rect(colour = "black", fill = NA, size = .5), 
    axis.text.x = element_blank(),
    axis.ticks = element_blank(),
    panel.grid  = element_blank()
  ) +
  geom_text(aes(x = 1.7, label = paste0(round(percentage, digits=0), " %")), size=3, 
            position = position_stack(vjust = 0.5))

方案2:保留边框并调整图例符号

如果需要饼图边框,通过guides()隐藏color的文本符号,避免和fill图例叠加:

ggplot(df.connexuniv.location, aes(x="", y=percentage, fill=uniconnex, color=uniconnex)) + 
  geom_bar(width=1, stat="identity")  +
  coord_polar("y", start=0, direction=-1) + facet_wrap(~location) +
  scale_fill_manual(
    values=c("grey20","grey60", "grey90","grey99"),
    name = "Connection to university", 
    labels=levels(df.connexuniv.location$uniconnex)
  ) +
  scale_color_manual(
    values=rep("grey20",4),
    name = "Connection to university"
  ) +
  labs(x=" ", y="percentage of audience") +
  theme(
    panel.border = element_rect(linetype = "solid", colour="black", linewidth=.5, fill = NA), 
    panel.background=element_rect(fill="grey97"), 
    strip.background = element_rect(colour = "black", fill = NA, size = .5), 
    axis.text.x = element_blank(),
    axis.ticks = element_blank(),
    panel.grid  = element_blank()
  ) +
  geom_text(aes(x = 1.7, label = paste0(round(percentage, digits=0), " %")), size=3, 
            position = position_stack(vjust = 0.5)) +
  guides(color = guide_legend(override.aes = list(shape = NA)))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 13:18:11