R編程語言有許多庫來創(chuàng)建圖表。 餅圖是將值表示為具有不同顏色的圓的切片。 切片被標記,并且對應于每個片的數(shù)字也在圖表中表示。
使用R語言創(chuàng)建餅圖的基本語法是 -
pie(x, labels, radius, main, col, clockwise)
以下是所使用的參數(shù)的描述 -
x是包含餅圖中使用的數(shù)值的向量。
labels用于給出切片的描述。
radius表示餅圖圓的半徑(值-1和+1之間)。
main表示圖表的標題。
col表示調色板。
clockwise是指示片段是順時針還是逆時針繪制的邏輯值。
使用輸入向量和標簽創(chuàng)建一個非常簡單的餅圖。 以下腳本將創(chuàng)建并保存當前R語言工作目錄中的餅圖。
# Create data for the graph. x <- c(21, 62, 10, 53) labels <- c("London", "New York", "Singapore", "Mumbai") # Give the chart file a name. png(file = "city.jpg") # Plot the chart. pie(x,labels) # Save the file. dev.off()
當我們執(zhí)行上面的代碼,它產生以下結果 -
我們可以通過向函數(shù)中添加更多參數(shù)來擴展圖表的功能。 我們將使用參數(shù)main向圖表添加標題,另一個參數(shù)是col,它將在繪制圖表時使用彩虹色板。 托盤的長度應與圖表中的值的數(shù)量相同。 因此,我們使用length(x)。
以下腳本將創(chuàng)建并保存當前R語言工作目錄中的餅圖。
# Create data for the graph. x <- c(21, 62, 10, 53) labels <- c("London", "New York", "Singapore", "Mumbai") # Give the chart file a name. png(file = "city_title_colours.jpg") # Plot the chart with title and rainbow color pallet. pie(x, labels, main = "City pie chart", col = rainbow(length(x))) # Save the file. dev.off()
當我們執(zhí)行上面的代碼,它產生以下結果 -
我們可以通過創(chuàng)建其他圖表變量來添加切片百分比和圖表圖例。
# Create data for the graph. x <- c(21, 62, 10,53) labels <- c("London","New York","Singapore","Mumbai") piepercent<- round(100*x/sum(x), 1) # Give the chart file a name. png(file = "city_percentage_legends.jpg") # Plot the chart. pie(x, labels = piepercent, main = "City pie chart",col = rainbow(length(x))) legend("topright", c("London","New York","Singapore","Mumbai"), cex = 0.8, fill = rainbow(length(x))) # Save the file. dev.off()
當我們執(zhí)行上面的代碼,它產生以下結果 -
可以使用其他軟件包繪制具有3個維度的餅圖。 軟件包plotrix有一個名為pie3D()的函數(shù),用于此。
# Get the library. library(plotrix) # Create data for the graph. x <- c(21, 62, 10,53) lbl <- c("London","New York","Singapore","Mumbai") # Give the chart file a name. png(file = "3d_pie_chart.jpg") # Plot the chart. pie3D(x,labels = lbl,explode = 0.1, main = "Pie Chart of Countries ") # Save the file. dev.off()
當我們執(zhí)行上面的代碼,它產生以下結果 -
更多建議: