【问题标题】:Why can't i plot an actual pie chart with percentages?为什么我不能绘制带有百分比的实际饼图?
【发布时间】:2020-12-11 10:42:00
【问题描述】:

我的数据集 Q6.1 中有两列,

 count(market_segment)  market_segment
1 201                   Complementary
2 2309                  Corporate
3 6513                  Direct
4 5836                  Groups
5 7472                  Offline TA/TO
6 17729                 Online TA

Showing 1 to 6 of 6 entries, 2 total columns

我正在使用此代码

ggplot(Q6.1, aes(x="", y= 'count(market_segment)', fill = market_segment))+ 
  geom_bar(stat="identity", width=1)+coord_polar("y", start=0)+
   geom_text(aes(label = paste0('count(market_segment')))

【问题讨论】:

  • 您好,欢迎来到堆栈溢出。我们是互联网上的陌生人,没有您的数据,也没有可以诊断的结果图的图片。您介意在代码示例中包含数据示例吗?通过复制粘贴dput(Q6.1)的输出,可以轻松共享数据片段

标签: r ggplot2 pie-chart


【解决方案1】:

您需要使用coord_polar将条形图转换为饼图,并使用geom_text添加百分比标签。鉴于列名笨拙,也许您还应该先将其转换为比例:

library(ggplot2)

df$percent <- df$`count(market_segment)`/ sum(df$`count(market_segment)`)

ggplot(df, aes(x = 1, y = percent, fill = market_segment)) + 
  geom_col(color = "gray90", width = 1) +
  geom_text(aes(x = c(1.1, rep(1, 5)), label = scales::percent(percent)),
            position = position_stack(vjust = 0.5)) +
  coord_polar(theta = "y") +
  scale_fill_brewer(palette = "Pastel1", name = "Market segment") +
  theme_void()

【讨论】:

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