【问题标题】:Plotting pie charts in ggplot2在ggplot2中绘制饼图
【发布时间】:2018-04-24 14:05:08
【问题描述】:

我想绘制一个合适的饼图。不过,本站之前的大部分问题都是来自stat = identity。如何绘制像图 2 一样的正常饼图,其角度与cut 的比例成正比?我正在使用来自 ggplot2 的 diamonds 数据框。

ggplot(data = diamonds, mapping = aes(x = cut, fill = cut)) + 
    geom_bar(width = 1) + coord_polar(theta = "x")

图表 1

ggplot(data = diamonds, mapping = aes(x = cut, y=..prop.., fill = cut)) + 
    geom_bar(width = 1) + coord_polar(theta = "x")

图表 2

ggplot(data = diamonds, mapping = aes(x = cut, fill = cut)) + 
    geom_bar()

图 3

【问题讨论】:

    标签: r plot ggplot2 pie-chart


    【解决方案1】:

    我们可以先计算每个cut组的百分比。我为此任务使用了dplyr 包。

    library(ggplot2)
    library(dplyr)
    
    # Calculate the percentage of each group
    diamonds_summary <- diamonds %>%
      group_by(cut) %>%
      summarise(Percent = n()/nrow(.) * 100)
    

    之后,我们可以绘制饼图。 scale_y_continuous(breaks = round(cumsum(rev(diamonds_summary$Percent)), 1))是根据累计百分比设置坐标轴标签。

    ggplot(data = diamonds_summary, mapping = aes(x = "", y = Percent, fill = cut)) + 
      geom_bar(width = 1, stat = "identity") + 
      scale_y_continuous(breaks = round(cumsum(rev(diamonds_summary$Percent)), 1)) +
      coord_polar("y", start = 0)
    

    这是结果。

    【讨论】:

      【解决方案2】:

      这个怎么样?

      ggplot(diamonds, aes(x = "", fill = cut)) + 
        geom_bar() +
        coord_polar(theta = "y")
      

      它产生:

      https://imgur.com/a/leSmIPT

      【讨论】:

      • 你可以在帖子中嵌入照片吗?
      • 他们不让我发布图片。您可以在 RStudio 中运行代码(只要加载了 ggplot2)。
      猜你喜欢
      • 1970-01-01
      • 2022-08-13
      • 1970-01-01
      • 2011-05-22
      • 1970-01-01
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多