how to change the legend sharp to circle

34 views Asked by At
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)
)

code is here. Want to change the shape from square to circle.

That is: In the output, I want to change "blue square" before "Caesar Salad" to "blue circle". Thanks

1

There are 1 answers

0
stefan On

The symbol(s) used in the legend are detereminded by the key glyph of the geom which in case of geom_bar is a rectangle. But you can change that with the key_glyph= argument of the geom, i.e. to get circles you can use key_glyph = "point". However, as the default point shape does not support a fill aes we have to switch to a shape which supports fill aka shape=21 which can be done with the override.aes argument of guide_legend. Additionally I increased the size of the "points".

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)))