新聞中心
r編程語言有許多庫來創(chuàng)建圖表。 餅圖是將值表示為具有不同顏色的圓的切片。 切片被標(biāo)記,并且對應(yīng)于每個片的數(shù)字也在圖表中表示。
在r語言中,餅圖是使用
pie()函數(shù)創(chuàng)建的,它使用正數(shù)作為向量輸入。 附加參數(shù)用于控制標(biāo)簽,顏色,標(biāo)題等。
語法
使用R語言創(chuàng)建餅圖的基本語法是 -
pie(x, labels, radius, main, col, clockwise)
以下是所使用的參數(shù)的描述 -
-
x是包含餅圖中使用的數(shù)值的向量。
-
labels用于給出切片的描述。
-
radius表示餅圖圓的半徑(值-1和+1之間)。
-
main表示圖表的標(biāo)題。
-
col表示調(diào)色板。
-
clockwise是指示片段是順時針還是逆時針繪制的邏輯值。
例
使用輸入向量和標(biāo)簽創(chuàng)建一個非常簡單的餅圖。 以下腳本將創(chuàng)建并保存當(dā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()
當(dāng)我們執(zhí)行上面的代碼,它產(chǎn)生以下結(jié)果 -
餅圖標(biāo)題和顏色
我們可以通過向函數(shù)中添加更多參數(shù)來擴(kuò)展圖表的功能。 我們將使用參數(shù)main向圖表添加標(biāo)題,另一個參數(shù)是col,它將在繪制圖表時使用彩虹色板。 托盤的長度應(yīng)與圖表中的值的數(shù)量相同。 因此,我們使用length(x)。
例
以下腳本將創(chuàng)建并保存當(dā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()
當(dāng)我們執(zhí)行上面的代碼,它產(chǎn)生以下結(jié)果 -
切片百分比和圖表圖例
我們可以通過創(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()
當(dāng)我們執(zhí)行上面的代碼,它產(chǎn)生以下結(jié)果 -
3D餅圖
可以使用其他軟件包繪制具有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()
當(dāng)我們執(zhí)行上面的代碼,它產(chǎn)生以下結(jié)果 -
分享題目:創(chuàng)新互聯(lián)R語言教程:R語言餅狀圖
文章出自:http://www.dlmjj.cn/article/dpehppj.html


咨詢
建站咨詢
