R編程語言中有許多庫用來創(chuàng)建圖表。餅狀圖是以不同顏色的圓的切片表示的值。這些切片被標(biāo)記,并且每個切片對應(yīng)的數(shù)字也在圖表中表示。
在R中,使用將正數(shù)作為向量輸入的pie()函數(shù)創(chuàng)建餅狀圖。附加參數(shù)用于控制標(biāo)簽,顏色,標(biāo)題等。
語法
使用R編程語言創(chuàng)建餅圖的基本語法是 -
pie(x, labels, radius, main, col, clockwise)
以下是使用的參數(shù)的描述 -
-1和+1之間的值)。使用輸入向量和標(biāo)簽創(chuàng)建一個非常簡單的餅狀圖。以下腳本將創(chuàng)建餅圖片并保存在當(dāng)前R工作目錄中。假設(shè)下是一個統(tǒng)計(jì)年齡段的代碼 -
# Create data for the graph.
x <- c(11, 30, 39, 20)
labels <- c("70后", "80后", "90后", "00后")
# Give the chart file a name.
png(file = "birth_of_age.jpg")
# Plot the chart.
pie(x,labels)
# Save the file.
dev.off()
當(dāng)我們執(zhí)行上述代碼時,會產(chǎn)生以下結(jié)果(圖片) -

可以通過向函數(shù)添加更多參數(shù)來擴(kuò)展圖表的特征。我們將使用參數(shù)main向圖表添加標(biāo)題,另一個參數(shù)是col,在繪制圖表時將使用彩虹色托盤。托盤的長度應(yīng)與圖表的數(shù)量相同。 因此我們使用length(x)。
例子
以下腳本將創(chuàng)建一個餅圖圖片文件(age_title_colours.jpg)并保存當(dāng)前R工作目錄中。
# Create data for the graph.
x <- c(11, 30, 39, 20)
labels <- c("70后", "80后", "90后", "00后")
# Give the chart file a name.
png(file = "age_title_colours.jpg")
# Plot the chart with title and rainbow color pallet.
pie(x, labels, main = "出生年齡段 - 餅狀圖", col = rainbow(length(x)))
# Save the file.
dev.off()
當(dāng)我們執(zhí)行上述代碼時,會產(chǎn)生以下結(jié)果 -

我們可以通過創(chuàng)建附加的圖表變量來添加切片百分比和圖表圖例。參考以下代碼實(shí)現(xiàn) -
# Create data for the graph.
x <- c(21, 62, 10,53)
labels <- c("70后", "80后", "90后", "00后")
piepercent<- paste(round(100*x/sum(x), 2), "%")
# Give the chart file a name.
png(file = "age_percentage_legends.jpg")
# Plot the chart.
pie(x, labels = piepercent, main = "出生年齡段 - 餅狀圖",col = rainbow(length(x)))
legend("topright", c("70后","80后","90后","00后"), cex = 0.8,
fill = rainbow(length(x)))
# Save the file.
dev.off()
當(dāng)我們執(zhí)行上述代碼時,會產(chǎn)生以下結(jié)果 -

可以使用附加包來繪制具有3個維度的餅圖。軟件包plotrix中有一個名為pie3D()的函數(shù),用于此效果。參考以下代碼 -
注: 如果沒有安裝軟件庫:
plotrix,可先執(zhí)行install.packages("plotrix")來安裝。
# Get the library.
library("plotrix")
# Create data for the graph.
x <- c(21, 62, 10,53)
lbl <- c("70后", "80后", "90后", "00后")
# Give the chart file a name.
png(file = "3d_pie_chart.jpg")
# Plot the chart.
pie3D(x,labels = lbl,explode = 0.1, main = "出生年齡段 - 餅狀圖")
# Save the file.
dev.off()
當(dāng)我們執(zhí)行上述代碼時,會產(chǎn)生以下結(jié)果 -
