donut chart using R and ggplot2
HTML-код
- Опубликовано: 21 авг 2024
- #donutchart #ggplot2 #rprogramming #datavisulaistion # beautifulplots
this video describes how to plot donut chart to show contributions of categories to the whole. This is suitable for plotting a categorical axis and a numeric axis.
donut charts are pie charts with inner portions removed out. It is prepared by using geom_rect() and polar coordinate system. the code used is as follows:
Create test data.
data = data.frame(
crop=rep("Chick Pea Desi",times=4),
category=c("CPvar1", "CPvar2", "CPvar3","CPvar4"),
count=c(15, 27, 34, 46)
)
data # to print data
load library
library(ggplot2)
ggplot(data, aes(crop,count, fill=category, xmax=4, xmin=2,))+
geom_bar(stat="identity")+
coord_polar(theta="y")
lets count proportions
data$fraction = data$count/sum(data$count)
data
Compute the cumulative proportions (top of each rectangle)
data$ymax = cumsum(data$fraction)
data
Compute the bottom of each rectangle
data$ymin = c(0, head(data$ymax, n=-1))
data
#compute label position
data$labelPosition= (data$ymax+data$ymin)/2
data
#get data label
data$label= paste0(data$category,"
Value=", data$count)
data
the plot
ggplot(data,aes(ymax=ymax,ymin=ymin,xmax=4, xmin=2, fill=category))+
geom_rect()+
coord_polar(theta="y")+
xlim(c(0,4))+
theme_void()+
geom_text(aes(y=labelPosition,label=label),x=3,size=3)+
theme(legend.position = "none")+
scale_fill_brewer(pallete=2)