ggplot2 - get annotations in legend

2019-07-15 06:23发布

问题:

I'm working with a dataframe and using ggplot to generate a pie chart.

df <- data.frame(Make=c('toyota','toyota','honda','honda','jeep','jeep','jeep','accura','accura'),
                 Model=c('camry','corolla','city','accord','compass', 'wrangler','renegade','x1', 'x3'),
                 Cnt=c(10, 4, 8, 13, 3, 5, 1, 2, 1))
row_threshold = 2
dfc <- df %>%
  group_by(Make) %>%
  summarise(volume = sum(Cnt)) %>%
  mutate(share=volume/sum(volume)*100.0) %>%
  arrange(desc(volume))


dfc$Make <- factor(dfc$Make, levels = rev(as.character(dfc$Make)))
pie <- ggplot(dfc[1:10, ], aes("", share, fill = Make)) +
  geom_bar(width = 1, size = 1, color = "white", stat = "identity") +
  coord_polar("y") +
  geom_text(aes(label = paste0(round(share), "%")), 
            position = position_stack(vjust = 0.5)) +
  labs(x = NULL, y = NULL, fill = NULL, 
       title = "Market Share") +
  guides(fill = guide_legend(reverse = TRUE)) +
  theme_classic() +
  theme(axis.line = element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank(),
        plot.title = element_text(hjust = 0.5, color = "#666666")) +
  scale_color_brewer(palette = "Paired")

this gives me a pie chart as below - how do I add %share along with the Make labels like honda (45%) instead of just honda

回答1:

This can be achieved by adding breaks and labels to the scale_fill_brewer.

First of all you mapped Make to fill so to control the color you need to use a fill_scale. Secondly if you want to provide custom legend entries define the keys present in the legend in breaks and the new names in labels :

library(ggplot2)


ggplot(dfc[1:10, ], aes("", share, fill = Make)) +
  geom_bar(width = 1, size = 1, color = "white", stat = "identity") +
  coord_polar("y") +
  geom_text(aes(label = paste0(round(share), "%")), 
            position = position_stack(vjust = 0.5)) +
  labs(x = NULL, y = NULL, fill = NULL, 
       title = "Market Share") +
  guides(fill = guide_legend(reverse = TRUE)) +
  theme_classic() +
  theme(axis.line = element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank(),
        plot.title = element_text(hjust = 0.5, color = "#666666")) +
   scale_fill_brewer(palette = "Paired",
                     labels = rev(paste0(dfc$Make, " (", round(dfc$share), "%)")),
                     breaks = rev(dfc$Make))



标签: r ggplot2