【问题标题】:R percent labels on pie chart [duplicate]饼图上的 R 百分比标签 [重复]
【发布时间】:2018-02-18 12:10:54
【问题描述】:

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

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

【问题讨论】:

标签: r ggplot2 shiny pie-chart


【解决方案1】:

使用geom_text 和position_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")

上面的代码生成这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多