r 带 aes (..count..)/sum(..count..) 的饼图

r pie chart with aes (..count..)/sum(..count..)

我有兴趣直接从数据集中在 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")

这是在创建如下所示的极坐标图

我期待的是这样的情节

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

你可以试试:

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()

这对你有用吗?

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 创建