【问题标题】:ggplot2 - get annotations in legendggplot2 - 在图例中获取注释
【发布时间】:2017-12-12 16:30:50
【问题描述】:

我正在使用数据框并使用 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

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

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

    首先,您将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))
    

    【讨论】:

    • 添加了标签,但是标签的顺序颠倒了。
    • @user3206440 最简单的解决方案是将rev 添加到labelsbreaks 参数中。 breaks 中指定的元素顺序决定了图例键条目的顺序。而labels 参数需要匹配breaks 参数。
    猜你喜欢
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多