ggplot2 - 获取图例中的注释

use*_*440 3 r ggplot2

我正在使用数据框并使用 ggplot 生成饼图。

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")
Run Code Online (Sandbox Code Playgroud)

这给了我一个饼图,如下所示 - 我如何将 %share 与Make标签一起添加,honda (45%)而不仅仅是honda

在此处输入图片说明

mis*_*use 5

这可以通过将breaks和添加labelsscale_fill_brewer.

首先你映射Makefillso 来控制你需要使用的颜色fill_scale。其次,如果您想提供自定义图例条目,请定义图例中存在的键breaks和新名称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))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明