饼图上的R百分比标签[重复]

时间:2022-12-03 17:52:10

This question already has an answer here:

这个问题在这里已有答案:

I'm trying to add some percent labels to a pie chart but any of the solutions works. The thing is that the chart displays the number of tasks completed grouped by category.

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

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

饼图上的R百分比标签[重复]

1 个解决方案

#1


2  

Using geom_text with position_stack to adjust the label locations would work.

使用带有position_stack的geom_text来调整标签位置会起作用。

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")

The codes above generate this:

上面的代码生成:

饼图上的R百分比标签[重复]

You might want to change the y-axis from counts to percentages since you are labeling the latter. In that case, change the values passed to ggplot accordingly.

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

#1


2  

Using geom_text with position_stack to adjust the label locations would work.

使用带有position_stack的geom_text来调整标签位置会起作用。

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")

The codes above generate this:

上面的代码生成:

饼图上的R百分比标签[重复]

You might want to change the y-axis from counts to percentages since you are labeling the latter. In that case, change the values passed to ggplot accordingly.

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