R语言饼状图

R编程语言中有许多库用来创建图表。饼状图是以不同颜色的圆的切片表示的值。这些切片被标记,并且每个切片对应的数字也在图表中表示。

在R中,使用将正数作为向量输入的pie()函数创建饼状图。附加参数用于控制标签,颜色,标题等。

语法

使用R编程语言创建饼图的基本语法是 -

pie(x, labels, radius, main, col, clockwise)

以下是使用的参数的描述 -

  • x - 是包含饼图中使用的数值的向量。
  • labels - 用于描述切片的标签。
  • radius - 用来表示饼图圆的半径(-1+1之间的值)。
  • main - 用来表示图表的标题。
  • col - 表示调色板。
  • clockwise - 是一个逻辑值,指示片是顺时针还是逆时针绘制。

例子

使用输入向量和标签创建一个非常简单的饼状图。以下脚本将创建饼图片并保存在当前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 = "birth_of_age.jpg")

# Plot the chart.
pie(x,labels)

# Save the file.
dev.off()

当我们执行上述代码时,会产生以下结果(图片) -

饼图标题和颜色

可以通过向函数添加更多参数来扩展图表的特征。我们将使用参数main向图表添加标题,另一个参数是col,在绘制图表时将使用彩虹色托盘。托盘的长度应与图表的数量相同。 因此我们使用length(x)

例子

以下脚本将创建一个饼图图片文件(age_title_colours.jpg)并保存当前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()

当我们执行上述代码时,会产生以下结果 -

切片百分比和图表图例

我们可以通过创建附加的图表变量来添加切片百分比和图表图例。参考以下代码实现 -

# 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()

当我们执行上述代码时,会产生以下结果 -

3D饼图

可以使用附加包来绘制具有3个维度的饼图。软件包plotrix中有一个名为pie3D()的函数,用于此效果。参考以下代码 -

注: 如果没有安装软件库:plotrix,可先执行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()

当我们执行上述代码时,会产生以下结果 -


上一篇:R语言连接数据库(MySQL)

下一篇:R语言条形图

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程