How to plot pie chart in R

created at 07-01-2021 views: 2

Data structure

The data structure is like bellow:

Data structure

1. Run R, set the color of the pie chart first, then read the data of the target file, call pie() to draw the abundance composition of the main bacterial categories in the sample a1, the specific code is as follows:

color=c( "#3C5488B2","#00A087B2", 
         "#8491B4B2", "#DC0000B2", 
         "darkolivegreen1", "lightskyblue", 
         "darkgreen", "deeppink", "khaki2", 
         "firebrick", "brown1", "darkorange1", 
         "cyan1", "royalblue4", "darksalmon", 
         "darkgoldenrod1", "darkseagreen", "darkorchid")
phylum <- read.delim('phylum.txt', sep = '\t', stringsAsFactors = FALSE, check.names = FALSE)
# pie(), you can use "?pie" to view the command details
pie(phylum$a1, col =color[1:length(unique(phylum$phylum))],
     labels = phylum$phylum, font = 3, main ='Sample: a1\nPhylum level')

 pie chart

2. Using the test data of the first step, call the plotrix package (the package can draw a 3D effect pie chart), and enter the command pie3D(). The specific code is as follows:

#pie3D(), you can use ?pie3D to view the command details

pie3D(phylum$a1, col = c('#8DD3C7','#FFFFB3','#BEBADA','#FB8072','#80B1D3','#FDB462'),
     explode = 0.05, height = 0.1, radius = 0.85, labels = phylum$phylum, labelcex = 1, main ='Sample: a1\nPhylum level')


3. Following the test data read in the previous step, call the fan.plot() command in the plotrix package to further draw the superimposed fan graph. 

The specific code is as follows:

# fan.plot(), you can use ?fan.plot to view the command details

fan.plot(phylum$a1, col = c('#8DD3C7','#FFFFB3','#BEBADA','#FB8072','#80B1D3','#FDB462'),
     labels = phylum$phylum, main ='Sample: a1\nPhylum level')

 fan graph

Note: The width of the sector is important here, and the radius is of little significance.

4. I believe everyone is familiar with this package. We introduced it in the last tweet. Of course, it can also be used to draw a pie chart. The specific code is as follows:


p <- ggplot(phylum, aes(x = '', y = a1, fill = phylum)) + 
geom_bar(stat = 'identity', width = 1) +
coord_polar(theta = 'y') +
scale_fill_manual(values = rev(c('#8DD3C7', '#FFFFB3', '#BEBADA', '#FB8072', '#80B1D3', '#FDB462'))) +
theme(panel.grid = element_blank(), panel.background = element_blank(), axis.text.x = element_blank(), plot.title = element_text(hjust = 0.5)) +
theme(legend.text = element_text(face = 'italic'), legend.title = element_blank()) +
labs(x = '', y = '', title = 'Sample: a1', fill = 'Phylum')


ggplot2 pie chart

Please log in to leave a comment.