简体   繁体   English

在饼图中添加值和百分比

[英]Adding values and percentages to pie chart

I'm trying to make a pie chart breaking down the split in values between 3 different categories (And yes I know a stacked bar chart would be better, but I don't really have a choice in the matter). 我正在尝试制作一个饼图,以分解3个不同类别之间的值划分(是的,我知道堆积的条形图会更好,但是我对此没有选择)。 I figured out how to make the pie using +coord_polar on a stacked bar plot, and hide the ticks/axis labels, but I need to include that actual values, as well as percentage of total, within each slice of the pie chart, and I'm not sure how to do that. 我想出了如何在堆叠的条形图上使用+ coord_polar制作饼图,并隐藏刻度/轴标签的方法,但是我需要在饼图的每个切片中包括该实际值以及总计值,以及我不确定该怎么做。 Here's the code I'm using (the data I'm working with is confidential, so I've replaced it with some simulated data). 这是我正在使用的代码(正在使用的数据是机密的,因此我已将其替换为一些模拟数据)。

library(ggplot2)

simuldata <- data.frame(Category = LETTERS[1:3], 
                        value = c(196, 149,127))

piechart <- ggplot(simuldata, aes(x="", y=value, fill=Category)) +
  geom_bar(width=1, stat="identity") +
  coord_polar("y", start=0) +
  xlab("") +
  ylab("Value") +
  theme(axis.text.x=element_blank(),axis.ticks.x=element_blank())

piechart

哪个产生这张图

How would I go about adding the values and percentages to each slice? 如何将值和百分比添加到每个切片中?

This is super-straightforward with the ggstatsplot package function ggpiestats ( https://cran.r-project.org/web/packages/ggstatsplot/vignettes/ggpiestats.html ): ggstatsplot包函数ggpiestatshttps://cran.r-project.org/web/packages/ggstatsplot/vignettes/ggpiestats.html )非常简单易懂:

# data
simuldata <- data.frame(Category = LETTERS[1:3],
                        value = c(196, 149, 127))

# plot
ggstatsplot::ggpiestats(data = simuldata,
                        main = Category,
                        counts = value)

Created on 2018-10-11 by the reprex package (v0.2.1) reprex软件包 (v0.2.1)创建于2018-10-11

You can add a geom_text() layer, positioning each label to be stacked & vertically aligned in the middle: 您可以添加geom_text()层,将每个要堆叠的标签放置在中间并垂直对齐:

piechart +
  geom_text(aes(label = paste0(value,
                               " (",
                               scales::percent(value / sum(value)),
                               ")")),
            position = position_stack(vjust = 0.5))

情节

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM