【问题标题】:Creating piechart from a count column with percentage as labels从以百分比为标签的计数列创建饼图
【发布时间】:2017-12-27 19:58:30
【问题描述】:

我创建了一个包含 1 列值计数的列表:

ataques_tot <- count(t1$attacktype1_txt)
ataques_tot
                               x  freq
1                  Armed Assault 40223
2                  Assassination 18402
3              Bombing/Explosion 83073
4 Facility/Infrastructure Attack  9581
5                      Hijacking 11733
6                Unarmed Assault   913
7                        Unknown  6425

我想用百分比而不是计数来制作饼图。我试图将该列表带到 df,然后使用类似这样的东西:

ggpie(ataques_tot, "value", label = "group",
  fill = "group", color = "white")

但我很挣扎,也许这个选项已经在 ggplot2 上实现了......

我也试过这个:

pie <- ggplot(t1, aes(x = factor(1), fill = factor(attacktype1_txt))) +
  geom_bar(width = 1)
pie + coord_polar(theta = "y")

但它给了我一个计数,而不是分类变量的百分比。之后,我只需要为情节命名即可。

【问题讨论】:

    标签: r dataframe ggplot2 pie-chart


    【解决方案1】:

    计算百分比:

    d$perc <- round(100 * d$freq / sum(d$freq))
    

    然后绘制:

    ggplot(data = d, aes(x = 0, y = freq, fill = x)) + 
      geom_bar(stat = "identity") +
      geom_text(aes(label = perc), position = position_stack(vjust = 0.5)) +
      scale_x_continuous(expand = c(0,0)) +
      labs(fill = 'Type', x = NULL, y = NULL, title = 'Deaths', subtitle = 'in perventages') +
      coord_polar(theta = "y") +
      theme_minimal()
    

    给出:


    使用过的数据:

    d <- structure(list(x = c("Armed Assault", "Assassination", "Bombing/Explosion", "Facility/Infrastructure Attack", "Hijacking", "Unarmed Assault", "Unknown"),
                        freq = c(40223L, 18402L, 83073L, 9581L, 11733L, 913L, 6425L)),
                   .Names = c("x", "freq"), class = "data.frame", row.names = c(NA, -7L))
    

    【讨论】:

    • 谢谢,差不多了。如何删除中心的白色五边形并命名为轴和图例?
    • @Borja_042 查看有关如何删除空心中心和添加/删除标题的更新
    • 完全完美!!我用代码编辑我的帖子。谢谢!
    • @Borja_042 你不应该用解决方案编辑你的问题:绿色复选标记已经表明问题已解决
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多