R 饼图

饼图是一种圆形统计图,它被分成若干个扇形,用于说明数值比例。

饼图将数据可视化为整体的一部分,这可以成为一种有效的沟通工具。


在 R 中创建饼图

在 R 中,我们使用 pie() 函数创建饼图。例如,

expenditure <- c(600, 300, 150, 100, 200)

# pie chart of of expenditure vector
result <- pie(expenditure)

print(result)

输出

Create Pie Chart Output
创建饼图

在上面的示例中,我们使用了 pie() 函数来创建 expenditure 向量的饼图。

我们上面创建的饼图是简单朴素的,我们可以为饼图添加很多内容。


在 R 中为饼图添加标题

要在 R 中为饼图添加标题,我们在 pie() 函数中传入 main 参数。例如,

expenditure <- c(600, 300, 150, 100, 200)

result <- pie(expenditure,
  main = "Monthly Expenditure Breakdown"  
)

print(result)

输出

Add Title to Pie Chart in R Output
带标题的饼图

在上图中,我们可以看到我们已经为 expenditure 向量的饼图添加了标题。

result <- pie(expenditure
  main = "Monthly Expenditure Breakdown"  
)

这里,main 参数为我们的饼图添加了标题 "Monthly Expenditure Breakdown"


在 R 中为每个饼图扇形添加标签

我们在 pie() 中传入 labels 参数,为 R 中饼图的每个扇形提供标签。

例如,

expenditure <- c(600, 300, 150, 100, 200)

result <- pie(expenditure,
  main = "Monthly Expenditure Breakdown",
  labels = c("Housing", "Food", "Cloths", "Entertainment", "Other")
)

print(result)

输出

Add Label to Pie Chart Slice
带标签的饼图

在上面的示例中,我们使用了 labels 参数来为饼图的每个扇形提供名称。请注意代码,

pie(expenditure,
  labels = c("Housing", "Food", "Cloths", "Entertainment", "Other")
)

这里,我们将 "Housing" 分配给第一个向量项 600,将 "Food" 分配给第二个向量项 300,依此类推。


在 R 中更改饼图扇形的颜色

在 R 中,我们在 pie() 中传入 col 参数来更改每个饼图扇形的颜色。例如,

expenditure <- c(600, 300, 150, 100, 200)

result <- pie(expenditure,
  main = "Monthly Expenditure Breakdown",
  labels = c("Housing", "Food", "Cloths", "Entertainment", "Other"),
  col = c("red", "orange", "yellow", "blue", "green")
)

print(result)

输出

Change Pie Chart Color Output
更改饼图颜色

在上面的示例中,我们在 pie() 中使用了 col 参数来更改饼图每个扇形的颜色。

pie(expenditure,
  ...
  labels = c("Housing", "Food", "Cloths", "Entertainment", "Other"),
  col = c("red", "orange", "yellow", "blue", "green")
)

这里,我们提供了一个颜色向量,它对应于饼图的每个标签。


在 R 中创建 3D 饼图

为了创建 3D 饼图,首先我们需要导入 plotrix 包。然后,我们使用 pie3D() 函数来创建 3D 饼图。例如,

# import plotrix to use pie3D()
library(plotrix)

expenditure <- c(600, 300, 150, 100, 200)

result <- pie3D(expenditure,
  main = "Monthly Expenditure Breakdown",
  labels = c("Housing", "Food", "Cloths", "Entertainment", "Other"),
  col = c("red", "orange", "yellow", "blue", "green")
)

print(result)

输出

Create 3D Pie Chart Output
创建 3D 饼图

这里,我们使用了 pie3D() 函数来创建 3D 饼图。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战