个性化阅读
专注于IT技术分析

R饼图示例图解

本文概述

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

饼图是通过pie()函数创建的, 该函数以正数作为向量输入。附加参数用于控制标签, 颜色, 标题等。

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

输出

R饼图示例图解

标题和颜色

饼图具有更多功能, 可以通过在pie()函数中添加更多参数来使用。我们可以通过传递main参数来为饼图命名。它将饼图的标题告知pie()函数。除此之外, 我们可以通过传递col参数在绘制图表时使用彩虹色托盘。

注意:托盘的长度将与图表中的值相同。因此, 我们将使用length()函数。

让我们看一个示例, 以了解这些方法如何创建带有标题和颜色的精美饼图。

例子

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

输出

R饼图示例图解

切片百分比和图表图例

饼图还有两个附加属性, 即切片百分比和图表图例。我们可以用百分比的形式显示数据, 也可以通过使用legend()函数将图例添加到R中的绘图中。 legend()函数具有以下语法。

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

输出

R饼图示例图解

3维饼图

在R中, 我们还可以创建三维饼图。为此, R提供了一个plotrix包, 其pie3D()函数用于创建引人注目的3D饼图。 pie3D()函数的参数与pie()函数相同。让我们看一个示例, 以了解如何借助此功能创建3D饼图。

例子

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

输出

R饼图示例图解

例子

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

输出

R饼图示例图解

赞(0)
未经允许不得转载:srcmini » R饼图示例图解

评论 抢沙发

评论前必须登录!