在ggplot2中绘制饼图 [英] Plotting pie charts in ggplot2

查看:1213
本文介绍了在ggplot2中绘制饼图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想绘制一张适当的饼图。然而,这个网站上的大多数问题都是从 stat = identity 绘制的。如何绘制一个正常的饼图,如图2所示,角度与 cut 的比例成正比?我正在使用ggplot2中的钻石数据框。

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

图1

解决方案

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

  library(ggplot2) 
库(dplyr)

#计算每个组的百分比
diamonds_summary < - diamonds%>>%
group_by(cut)%>%
summary(Percent = n()/ nrow(。)* 100)

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

  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)

结果如下。




I want to plot a proper pie chart. However, most of the previous questions on this site were drawn from stat = identity. How can I plot a normal pie chart like graph 2 with the angle proportional to proportion of cut? I am using the diamonds data frame from ggplot2.

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

Graph 1

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

Graph 2

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

Graph 3

解决方案

We can first calculate the percentage of each cut group. I used the dplyr package for this task.

library(ggplot2)
library(dplyr)

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

After that, we can plot the pie chart. scale_y_continuous(breaks = round(cumsum(rev(diamonds_summary$Percent)), 1)) is to set the axis label based on cumulative percentage.

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)

Here is the result.

这篇关于在ggplot2中绘制饼图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆