r - ggplot2 - 获取图例中的注释

标签 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")

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

enter image description here

最佳答案

这可以通过向 scale_fill_brewer 添加 breakslabels 来实现。

首先,您将 Make 映射到 fill,因此要控制您需要使用 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))

enter image description here

关于r - ggplot2 - 获取图例中的注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47765280/

相关文章:

r - 将 gganimate 与 geom_point 和 geom_line 结合使用

r - 在 ggplot (R) 中手动设置 x 轴值

r - 在 y 轴上方添加空间而不用 expand()

r - 如何有效地按组聚合多个 data.table 列,一次 N 个,其中 N 是可变的

r - 从 r 中的多个列表制作二进制(存在/不存在)数据矩阵

R规范化然后在R中一起绘制两个直方图

r - 如何构建一个循环数据帧并转换其中数据的函数 (R)

r - 如何使用ggplot2填充stat_poly_eq方程(ggpmisc)的背景?

r - 将箭头添加到ggplot

r - geom_step 的空心直方图或分箱