如何将图例改为圆形

问题描述 投票:0回答:1
library(ggplot2)
food_choices <- c("Pizza", "Pasta", "Sushi", "Caesar Salad")
counts <- c(17, 10, 8, 11)
table <- data.frame(food_choices, counts) # Create data frame
colnames(table) <- c("Food", "Count")
# Pie Chart:
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 \n",
   fill = "Colour Choices") +
theme(
plot.title = element_text(hjust = 0.5),
legend.title = element_text(hjust = 0.5, face = "bold", size = 10)
)

代码在这里。想要将形状从方形更改为圆形。

即:在输出中,我想将“凯撒沙拉”之前的“蓝色方块”更改为“蓝色圆圈”。 谢谢

r ggplot2 legend geom-bar
1个回答
0
投票

图例中使用的符号由

geom
的键字形决定,在
geom_bar
的情况下是一个矩形。但是您可以使用
key_glyph=
geom
参数来更改它,即要获得圆圈,您可以使用
key_glyph = "point"
。然而,由于默认的点形状不支持
fill
aes,我们必须切换到支持
fill
又名
shape=21
的形状,这可以通过
override.aes
guide_legend
参数来完成。此外,我还增加了“点”的大小。

library(ggplot2)

ggplot(table, aes(x = "", y = Count, fill = Food)) +
  geom_bar(
    width = 1, stat = "identity",
    key_glyph = "point"
  ) +
  coord_polar(theta = "y", start = 0) +
  scale_fill_manual(
    values = c("Blue", "Red", "Green", "Orange")) +
  labs(
    x = "",
    y = "",
    title = "Favourite Food Survey \n",
    fill = "Colour Choices"
  ) +
  theme(
    plot.title = element_text(hjust = 0.5),
    legend.title = element_text(hjust = 0.5, face = "bold", size = 10)
  ) +
  guides(fill = guide_legend(override.aes = list(shape = 21, size = 6)))

© www.soinside.com 2019 - 2024. All rights reserved.