Search code examples
rdataframeggplot2pie-chart

Pie chart with multiple tags/info in ggplot2


I want to make a pie-chart in R visualizing four companies by their name and market cap. Preferably I want to do this using the ggplot2 package since I have used this for graphs and histograms etc previously. Below is an example of my data frame and my desired output.

This is an example of a representable data frame for my data:

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

Desired output (created in Excel):

enter image description here


Solution

  • This is pretty much what you've asked for, with labels for market cap and company name

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

    enter image description here