饼图上的R百分比标签

时间:2018-02-18 12:10:55

标签: r ggplot2 shiny pie-chart

我试图在饼图中添加一些百分比标签,但任何解决方案都有效。问题是图表显示按类别分组完成的任务数。

 output$plot2<-renderPlot({
ggplot(data=data[data$status=='100% completed',], aes(x=factor(1), fill=category))+
  geom_bar(width = 1)+
  coord_polar("y")

enter image description here

1 个答案:

答案 0 :(得分:2)

使用geom_textposition_stack来调整标签位置会有效。

library(ggplot2)
library(dplyr)

# Create a data frame which is able to replicate your plot
plot_frame <- data.frame(category = c("A", "B", "B", "C"))

# Get counts of categories
plot_frame <- plot_frame %>%
  group_by(category) %>%
  summarise(counts = n()) %>%
  mutate(percentages = counts/sum(counts)*100)

# Plot
ggplot(plot_frame, aes(x = factor(1), y = counts)) +
  geom_col(aes(fill = category), width = 1) +
  geom_text(aes(label = percentages), position = position_stack(vjust = 0.5)) +
  coord_polar("y")

上面的代码生成了这个:

Pie charts with percentages

您可能希望将y轴从counts更改为percentages,因为您要标记后者。在这种情况下,请相应地更改传递给ggplot的值。