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

如何将ggplot2饼图的图例形状从方形改为圆形

如何修改ggplot2饼图中单个图例项的形状为圆形

要将饼图图例里「Caesar Salad」前的方形替换为圆形,你可以通过guides()函数配合guide_legend()的override.aes参数,针对性指定该图例项的符号类型,其余项保持默认方形。以下是修改后的完整代码:

library(ggplot2)
food_choices <- c("Pizza", "Pasta", "Sushi", "Caesar Salad")
counts <- c(17, 10, 8, 11)
table <- data.frame(food_choices, counts) 
colnames(table) <- c("Food", "Count")

ggplot(table, aes(x = "", y = Count, fill = Food)) +
  geom_bar(width = 1, stat = "identity") +
  coord_polar(theta = "y", start = 0) +
  scale_fill_manual(values = c("Blue", "Red", "Green", "Orange")) +
  labs(x = "",
       y = "",
       title = "Favourite Food Survey",
       fill = "Colour Choices") +
  theme(
    plot.title = element_text(hjust = 0.5),
    legend.title = element_text(hjust = 0.5, face = "bold", size = 10)
  ) +
  # 核心修改:指定前三个图例项用方形,第四个(Caesar Salad)用圆形
  guides(fill = guide_legend(
    override.aes = list(
      key_glyph = c("rect", "rect", "rect", "circle")
    )
  ))

关键说明:

  • key_glyph参数接受字符向量,元素顺序与Food列的类别顺序完全对应,"rect"代表方形,"circle"代表圆形。
  • 如果需要调整圆形的大小或边框样式,可在override.aes中额外添加参数,比如size = c(1,1,1,2)让圆形更大,color = "black"给圆形添加黑色边框。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 20:38:20