【问题标题】:r pie chart with aes (..count..)/sum(..count..)r 饼图与 aes (..count..)/sum(..count..)
【发布时间】:2020-08-11 19:23:41
【问题描述】:

我有兴趣直接从数据集中在 r 中绘制饼图,而不是使用 table 函数。

这是我目前所拥有的

ggplot(iris, aes(x= Species)) + 
          geom_bar(aes(y = (..count..)/sum(..count..), fill=factor(..x..)), stat= "count")+
          geom_text(aes(label = scales::percent((..count..)/sum(..count..)),
                  y= ((..count..)/sum(..count..))), stat="count", vjust = -.25) +
           coord_polar(theta = "y",start = pi / 3, clip = "off")

这是创建一个像下面这样的极坐标图

我期待的是这样的情节

非常感谢任何关于我哪里出错的建议。提前致谢。

【问题讨论】:

    标签: r ggplot2 pie-chart


    【解决方案1】:

    你可以试试:

    ggplot(iris, aes(x = 1, fill = Species)) + 
              geom_bar(position = position_stack(),
                       width = 1, color = "white",
                       size = 2) +
              geom_text(aes(label = scales::percent((..count..) / sum(..count..))),
                        stat = "count", position = position_stack(vjust = 0.5)) +
              coord_polar(theta = "y", start = pi / 3, clip = "off") +
      theme_void()
    

    如果你对虹膜的随机子集做同样的事情,你会得到类似的结果:

    ggplot( iris[sample(nrow(iris), 20),], aes(x = 1, fill = Species)) + 
              geom_bar(position = position_stack(),
                       width = 1, color = "white",
                       size = 2) +
              geom_text(aes(label = scales::percent((..count..) / sum(..count..))),
                        stat = "count", position = position_stack(vjust = 0.5)) +
              coord_polar(theta = "y", start = pi / 3, clip = "off") +
      theme_void()
    

    【讨论】:

    • 这适用于上述玩具数据集,其中有 3 个因子或 3 个级别的分类变量。如果我将此解决方案应用于具有 2 个级别的变量,则该图表具有误导性,它显示 40% 和 60% 的大小相同:(
    • 我知道你说过你不想要额外的步骤,但在上述情况下,我相信使用我提供的解决方案将有助于解决这个问题。以防万一你需要一些东西而不是什么都没有。 :)
    • @Science11 查看我的更新。这应该可以解决问题。
    【解决方案2】:

    这对你有用吗?

    library(dplyr)
    library(ggplot2)
    library(scales)
    
    data <- iris %>% 
            group_by(Species) %>% 
            summarise(n = n()) %>% 
            mutate(freq = n / sum(n)) %>% 
            mutate(ypos = cumsum(freq)- 0.5*freq)
    
    
    data[,'freq']=round(data[,'freq'],2)
    
    ggplot(data, aes(x= "", y=freq, fill = Species)) + 
      geom_bar(stat="identity", width=1, color="white") +
      coord_polar("y", start=0) +
      theme_void() +
      geom_text(aes(y = ypos, label = percent(freq)), color = "white", size=6)+
      theme(legend.position="right")
    

    由reprex package (v0.3.0) 于 2020-08-11 创建

    【讨论】:

    • 我试图避免使用 group_by、summarise、mutate 等附加步骤。几乎就像 Allan 下面提出的那样
    猜你喜欢
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    • 2013-05-07
    • 2012-11-02
    • 2014-02-10
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多