餅圖在平時生活中很常見,但是在科研中椭更,相對于餅圖,他們更推薦使用條形圖或點圖蛾魄,因為相對于面積虑瀑,人們對長度的判斷更精確。也許由于這個原因滴须,R中餅圖的選項與其他統(tǒng)計軟件相比十分有限污它。
1. 簡單餅圖
pie(x, labels = names(x), edges = 200, radius = 0.8,
clockwise = FALSE, init.angle = if(clockwise) 90 else 0,
density = NULL, angle = 45, col = NULL, border = NULL,
lty = NULL, main = NULL, ...)
x是一個非負數(shù)值向量趾娃,表示每個扇形的面積赎线,而labels則是表示各扇形標簽的字符型向量曹步。
> phylum <- read.delim('/Users/kimhan/Desktop/phylum.txt', sep = '\t', stringsAsFactors = FALSE, check.names = FALSE)
> pie(phylum$a1, col = c('blue', 'orange', 'red', 'green2', 'purple', 'cyan'), labels = phylum$phylum, font = 3, main = 'Sample: a1\nPhylum level')
image
2. 繪制3D餅圖
plotrix包中提供了一個可繪制3D效果餅圖的命令pie3D()。
install.packages("plotrix")
> library(plotrix)
> pie3D(phylum$a1, col = c('blue', 'orange', 'red', 'green2', 'purple', 'cyan'), explode = 0.05, height = 0.1, radius = 0.85, labels = phylum$phylum, labelcex = 1, main = 'Sample: a1\nPhylum level')
image
3. ggplot()繪制餅圖
繪制一個餅圖之前魔市,需要繪制一個條形圖主届,該條形圖有多個分組,這就需要設(shè)置映射的x參數(shù)映射為一個常量因子待德,fill映射為分類因子君丁,即用geom_bar()繪制條形圖,然后使用coord_polar(theta = 'y')以y軸為基準將默認的笛卡爾坐標系轉(zhuǎn)化為極坐標樣式得到餅圖:
> ggplot(phylum, aes(x = '', y = a1, fill = phylum)) +
+ geom_bar(stat = 'identity', width = 1) +
+ coord_polar(theta = 'y')
Error: `data` must be uniquely named but has duplicate columns
> phylum[,4] <- NULL
> phylum
phylum a1 a2
1 Proteobacteria 6378 6708
2 Actinobacteria 662 557
3 Firmicutes 526 551
4 Bacteroidetes 469 392
5 Acidobacteria 212 149
6 Nitrospirae 61 27
> ggplot(phylum, aes(x = '', y = a1, fill = phylum)) +
+ geom_bar(stat = 'identity', width = 1) +
+ coord_polar(theta = 'y')
image