在ggplot2中绘制饼图
问题描述:
我想绘制一张适当的饼图。但是,此网站上的大多数以前的问题都是从stat = identity
中抽取的。如何绘制一个正常的饼图,如图2所示,角度与cut
的比例成正比?我正在使用ggplot2的diamonds
数据帧。在ggplot2中绘制饼图
ggplot(data = diamonds, mapping = aes(x = cut, fill = cut)) +
geom_bar(width = 1) + coord_polar(theta = "x")
ggplot(data = diamonds, mapping = aes(x = cut, y=..prop.., fill = cut)) +
geom_bar(width = 1) + coord_polar(theta = "x")
ggplot(data = diamonds, mapping = aes(x = cut, fill = cut)) +
geom_bar()
答
我们可以先计算出percen每个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)
这是结果。
这看起来像很多工作... – JetLag