# R饼图示例图解

## 本文概述

R编程语言具有几个用于创建图表的图形库。饼图以不同颜色的圆形切片的形式表示值。切片带有说明标签, 并且每个切片对应的数字也显示在图表中。但是, R文档中不建议使用饼图, 并且饼图的特性受到限制。作者建议在饼图中使用条形图或点图, 因为人们能够比长度更准确地测量长度。

pie()函数的语法如下：

``pie(X, Labels, Radius, Main, Col, Clockwise)``

1. X是一个向量, 其中包含饼图中使用的数值。
2. 标签用于对切片进行描述。
3. 半径描述饼图的半径。
4. Main描述图表的标题。
5. Col定义调色板。
6. 顺时针是一个逻辑值, 指示在其中绘制切片的顺时针或逆时针方向。

### 例子

``````# Creating data for the graph.
x <- c(20, 65, 15, 50)
labels <- c("India", "America", "Shri Lanka", "Nepal")
# Giving the chart file a name.
png(file = "Country.jpg")
# Plotting the chart.
pie(x, labels)
# Saving the file.
dev.off()``````

## 标题和颜色

### 例子

``````# Creating data for the graph.
x <- c(20, 65, 15, 50)
labels <- c("India", "America", "Shri Lanka", "Nepal")
# Giving the chart file a name.
png(file = "title_color.jpg")
# Plotting the chart.
pie(x, labels, main="Country Pie chart", col=rainbow(length(x)))
# Saving the file.
dev.off()``````

## 切片百分比和图表图例

``legend(x, y=NULL, legend, fill, col, bg)``

• x和y是用于定位图例的坐标。
• 图例是图例的文字
• fill是用于填充图例文本旁边的框的颜色。
• col定义图例文本之外的线条和点的颜色。
• bg是图例框的背景色。

### 例子

``````# Creating data for the graph.
x <- c(20, 65, 15, 50)
labels <- c("India", "America", "Shri Lanka", "Nepal")
pie_percent<- round(100*x/sum(x), 1)
# Giving the chart file a name.
png(file = "per_pie.jpg")
# Plotting the chart.
pie(x, labels = pie_percent, main = "Country Pie Chart", col = rainbow(length(x)))
legend("topright", c("India", "America", "Shri Lanka", "Nepal"), cex = 0.8, fill = rainbow(length(x)))
#Saving the file.
dev.off()``````

## 3维饼图

### 例子

``````# Getting the library.
library(plotrix)
# Creating data for the graph.
x <- c(20, 65, 15, 50, 45)
labels <- c("India", "America", "Shri Lanka", "Nepal", "Bhutan")
# Give the chart file a name.
png(file = "3d_pie_chart1.jpg")
# Plot the chart.
pie3D(x, labels = labels, explode = 0.1, main = "Country Pie Chart")
# Save the file.
dev.off()``````

### 例子

``````# Getting the library.
library(plotrix)
# Creating data for the graph.
x <- c(20, 65, 15, 50, 45)
labels <- c("India", "America", "Shri Lanka", "Nepal", "Bhutan")
pie_percent<- round(100*x/sum(x), 1)
# Giving the chart file a name.
png(file = "three_D_pie.jpg")
# Plotting the chart.
pie3D(x, labels = pie_percent, main = "Country Pie Chart", col = rainbow(length(x)))
legend("topright", c("India", "America", "Shri Lanka", "Nepal", "Bhutan"), cex = 0.8, fill = rainbow(length(x)))
#Saving the file.
dev.off()``````

• 回顶