【问题标题】:Add values to pie chart legend with ggplot2 in R在 R 中使用 ggplot2 向饼图图例添加值
【发布时间】:2021-01-14 11:56:58
【问题描述】:

我用 R 中的 ggplot 创建了一个饼图,绘制了 7 家公司(A 到 G)的“金额”。

数据和代码如下:

# Data
data=data.frame('Company'=(c("A","B","C","D","E","F","G")),'Amount'=c(30,20,10,5,5,2,1))
data=data %>% mutate(Company= factor(x = Company, levels = Company)) %>% 
  mutate(prop = Amount / sum(data$Amount) ) %>%  mutate(ypos = cumsum(prop)- 0.5*prop )

# Pie chart
library(ggplot2)
ggplot(data, aes(x="", y=Amount, fill= Company) )+ 
  geom_bar(width = 1, stat = "identity") + coord_polar("y", start=0,direction = -1) + theme_void() +
  #geom_text(aes(label = percent(prop) ), size=3, position=position_stack(vjust=0.5)) +
  labs(x = NULL, y = NULL, fill = NULL) + scale_fill_brewer(palette="Blues", direction=-1) +
  geom_text(aes(label = percent(prop) ), size=3, position=position_stack(vjust=0.5)) 

但是,F 和 G 的标签相互堆叠,因此我们无法正确读取值。

我想将这些标签放在图例中,使图例显示为:A (41.1%) B (27.4%) C (13.7%) 等。

【问题讨论】:

    标签: r ggplot2 legend pie-chart


    【解决方案1】:

    谢谢你,这行得通。

    我只需要将 subdata$legend_labs 修改为一个因子变量,以保持图例中的顺序(即从最高金额到最低金额)。

    【讨论】:

      【解决方案2】:

      这可以这样实现:

      1. 通过粘贴公司名称和比例来添加新列
      2. 在填充上映射这个新列
      library(ggplot2)
      library(dplyr)
      library(scales)
      
      # Data
      data=data.frame('Company'=(c("A","B","C","D","E","F","G")),'Amount'=c(30,20,10,5,5,2,1))
      data=data %>% mutate(Company= factor(x = Company, levels = Company)) %>% 
        mutate(prop = Amount / sum(data$Amount) ) %>%  
        mutate(ypos = cumsum(prop)- 0.5*prop) %>%
        mutate(legend_labs = paste0(Company, " (", percent(prop), ")"))
      
      # Pie chart
      library(ggplot2)
      ggplot(data, aes(x="", y=Amount, fill= legend_labs) )+ 
        geom_bar(width = 1, stat = "identity") + 
        coord_polar("y", start=0, direction = -1) + 
        theme_void() +
        labs(x = NULL, y = NULL, fill = NULL) + 
        scale_fill_brewer(palette="Blues", direction=-1) +
        geom_text(aes(label = percent(prop) ), size=3, position=position_stack(vjust=0.5)) 
      

      【讨论】:

      • 我认为这是一个很好的答案。谁能解释一下为什么它被否决了?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-11
      • 1970-01-01
      • 2022-08-13
      • 1970-01-01
      • 2019-08-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多