【问题标题】:Pie chart with multiple tags/info in ggplot2ggplot2中具有多个标签/信息的饼图
【发布时间】:2020-09-11 04:54:52
【问题描述】:

我想用 R 制作一个饼图,按名称和市值可视化四家公司。 最好我想使用 ggplot2 包来执行此操作,因为我之前已将其用于图形和直方图等。以下是我的数据框和所需输出的示例。

这是我的数据的可表示数据框的示例:

  Companies <- data.frame(
  Company = c("Company1", "Company2", "Company3", "Company4"),
  Market_cap = c(500, 200, 150, 90),
  Industry = c("Industry 1", "Industry 2", "Industry 3", "Industry 4"))

所需的输出(在 Excel 中创建):

【问题讨论】:

  • 你好@Andycode,到目前为止你尝试了什么?更容易看到究竟是什么不工作。

标签: r dataframe ggplot2 pie-chart


【解决方案1】:

这几乎就是您所要求的,带有市值和公司名称的标签

library(ggplot2)
library(dplyr)
Companies %>%
  mutate(Perc = Market_cap / sum(Market_cap)) %>%
  ggplot(aes(x = "", y = Perc, fill = Industry)) +
  geom_bar(stat = "identity", width = 1, color = "black") +
  coord_polar("y", start = 0) +
  geom_text(aes(label = paste0(Market_cap, "\n", Company)), position = position_stack(vjust = 0.5)) +
  labs(x = NULL, y = NULL, fill = NULL) +
  theme_classic() +
  theme(
    axis.line = element_blank(),
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    legend.position = "bottom"
  ) +
  scale_fill_manual(values=c("red", "blue", "green", "purple"))

【讨论】:

  • 谢谢!如何更改颜色并在它们之间添加边框?
  • @Andycode 我已经编辑了答案以更改颜色并添加黑色边框
  • 再次感谢,非常感谢!
【解决方案2】:

这应该可以帮助您入门 - 您可能需要稍微调整一下标签的位置。我引用了this question 作为开始。

Companies <- data.frame(
  Company = c("Company1", "Company2", "Company3", "Company4"),
  Market_cap = c(500, 200, 150, 90),
  Industry = c("Industry 1", "Industry 2", "Industry 3", "Industry 4"))

Companies$pos <- cumsum(Companies$Market_cap) - Companies$Market_cap/4
Companies$lab <- paste0(Companies$Company, " - ", Companies$Market_cap)

library(ggplot2)

ggplot(Companies, aes(factor(1), Market_cap, , fill = reorder(Industry, Market_cap))) +
  geom_bar(width = 1, stat = "identity") +
  geom_text(aes(x= factor(1), y=pos, label = lab)) +
  coord_polar("y", start = 0) +
  ylab("") +
  xlab("") +
  theme_bw() +
  theme(legend.position = "bottom",
        legend.direction = "horizontal",
        panel.grid = element_blank(),
        axis.text.y=element_blank(),
        axis.ticks = element_blank())

reprex package (v0.3.0) 于 2020 年 5 月 24 日创建

【讨论】:

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