我有一组大约 30 种不同工作的数据。每个工作都有不同数量的科目。
这是我的数据的
dput(pie_data)
:
structure(list(job = structure(1:33, levels = c("08", "09", "17",
"18", "19", "20", "23", "24", "25", "26", "27", "28", "31", "34",
"35", "36", "37", "38", "43", "46", "48", "63", "66", "71", "72",
"76", "78", "83", "85", "86", "88", "94", "96"), class = "factor"),
N = c(41L, 11L, 203L, 162L, 224L, 28L, 3L, 56L, 2L, 176L,
4L, 13L, 108L, 31L, 3L, 11L, 32L, 30L, 395L, 25L, 2L, 1L,
1L, 155L, 79L, 9L, 15L, 71L, 389L, 12L, 21L, 2L, 3L)), class = "data.frame", row.names = c(NA,
-33L))
我想绘制一个按降序排列的饼图,并在饼图中仅显示重要信息(例如百分比排名前 8 的职位及其职位代码)。
这是我尝试过的以及我生成的饼图
ggplot(pie_data, aes(x="", y= N, fill=job)) +
geom_bar(stat="identity", width=1, color = "white") +
coord_polar("y", start=0) +
theme_void()
虽然我喜欢饼图的色彩缤纷和彩虹般的形状,但我发现它是根据职位代码排序而不是每个职位中的科目数量。
很难识别女巫的颜色与其工作代码相匹配,因为我的数据中的工作太多了。我希望也许前 8 个热门职位可以有名称(职位代码)以及饼图上显示的比例,而其他不太受欢迎的职位则保持与上图相同的方式。
“降序”是指饼图中的项目从多到少排列。
ggplot2
似乎没有直观的方法来绘制饼图。如果有推荐的套餐我会很高兴知道。
你可以试试这个:
library(forcats)
library(ggplot2)
library(dplyr)
pie_data %>%
mutate(
job = fct_infreq(job, w = N),
label = ifelse(xtfrm(job)<=8, paste0(job,"\n",sprintf("%1.0f%%",100*N/sum(N))),"")
) %>%
ggplot(aes(x = 1, y = N, fill = job)) +
geom_col(width = 1, color = "white") +
geom_text(aes(x = 1.3, label = label), position = position_stack(vjust = 0.5)) +
coord_polar(theta = "y", direction = -1) +
theme_void() + theme(aspect.ratio = 1)
这里:
forcats::fct_infreq()
重新排序类别。ifelse(xtfrm(job)<=8,...,...)
选择为前 8 个创建标签文本 job
sggplot2::geom_col()
相当于 geom_bar(stat="identity")
position = position_stack(vjust = 0.5)
将文本放置在正确的位置x
”中的geom_text(aes(x = 1.3))
值