For this project, I created a donut chart that displays the market share of six pharmaceutical companies. The data are randomly generated via R.
Code can be found below.
# load library
library(ggplot2)
# Create the data frame
pharma_companies <- data.frame(
company_name = c("GSK", "Merck", "Pfizer", "Astrazeneca", "Eli Lilly", "Bayer"),
color = c("#FFA500", "#006400", "#0000FF", "#800080", "#FF0000", "#90EE90"), # hex color codes for orange, dark green, blue, purple, red, and light green
annual_sales = c(43, 48, 51, 35, 24, 27) # assumed to be in billions
)
# Calculate total sales
total_sales <- sum(pharma_companies$annual_sales)
# Calculate sales as a percentage of the total
pharma_companies$fraction <- (pharma_companies$annual_sales / total_sales)
# Compute the cumulative percentages (top of each rectangle)
pharma_companies$ymax <- cumsum(pharma_companies$fraction)
# Compute the bottom of each rectangle
pharma_companies$ymin <- c(0, head(pharma_companies$ymax, n=-1))
# Compute label position
pharma_companies$labelPosition <- (pharma_companies$ymax + pharma_companies$ymin) / 2
# Compute a good label
pharma_companies$label <- paste0(pharma_companies$company_name, "\n ", round(pharma_companies$fraction * 100, 2), "%")
# Create a named vector of colors
colors <- setNames(pharma_companies$color, pharma_companies$company_name)
# Make the plot
ggplot(pharma_companies, aes(ymax=ymax, ymin=ymin, xmax=4, xmin=3, fill=company_name)) +
geom_rect() +
geom_text( x=2, aes(y=labelPosition, label=label, color=company_name), size=6) + # x here controls label position (inner / outer)
scale_fill_manual(values = colors) +
scale_color_manual(values = colors) +
coord_polar(theta="y") +
xlim(c(-1, 4)) +
theme_void() +
theme(legend.position = "none")