课程表

R语言 基础教程

R语言 图表

R语言 数据接口

R语言 统计示例

工具箱
速查手册

R语言 饼状图

当前位置:免费教程 » 程序设计 » R语言

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

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

语法

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

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

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

  • x是包含饼图中使用的数值的向量。

  • labels用于给出切片的描述。

  • radius表示饼图圆的半径(值-1和+1之间)。

  • main表示图表的标题。

  • col表示调色板。

  • clockwise是指示片段是顺时针还是逆时针绘制的逻辑值。

使用输入向量和标签创建一个非常简单的饼图。 以下脚本将创建并保存当前R语言工作目录中的饼图。

  1. # Create data for the graph.
  2. x <- c(21, 62, 10, 53)
  3. labels <- c("London", "New York", "Singapore", "Mumbai")
  4.  
  5. # Give the chart file a name.
  6. png(file = "city.jpg")
  7.  
  8. # Plot the chart.
  9. pie(x,labels)
  10.  
  11. # Save the file.
  12. dev.off()

当我们执行上面的代码,它产生以下结果 -

馅饼的chatr,使用R

饼图标题和颜色

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

以下脚本将创建并保存当前R语言工作目录中的饼图。

  1. # Create data for the graph.
  2. x <- c(21, 62, 10, 53)
  3. labels <- c("London", "New York", "Singapore", "Mumbai")
  4.  
  5. # Give the chart file a name.
  6. png(file = "city_title_colours.jpg")
  7.  
  8. # Plot the chart with title and rainbow color pallet.
  9. pie(x, labels, main = "City pie chart", col = rainbow(length(x)))
  10.  
  11. # Save the file.
  12. dev.off()

当我们执行上面的代码,它产生以下结果 -

饼图以标题和颜色

切片百分比和图表图例

我们可以通过创建其他图表变量来添加切片百分比和图表图例。

  1. # Create data for the graph.
  2. x <- c(21, 62, 10,53)
  3. labels <- c("London","New York","Singapore","Mumbai")
  4.  
  5. piepercent<- round(100*x/sum(x), 1)
  6.  
  7. # Give the chart file a name.
  8. png(file = "city_percentage_legends.jpg")
  9.  
  10. # Plot the chart.
  11. pie(x, labels = piepercent, main = "City pie chart",col = rainbow(length(x)))
  12. legend("topright", c("London","New York","Singapore","Mumbai"), cex = 0.8,
  13. fill = rainbow(length(x)))
  14.  
  15. # Save the file.
  16. dev.off()

当我们执行上面的代码,它产生以下结果 -

饼图用百分比和标签

3D饼图

可以使用其他软件包绘制具有3个维度的饼图。 软件包plotrix有一个名为pie3D()的函数,用于此。

  1. # Get the library.
  2. library(plotrix)
  3.  
  4. # Create data for the graph.
  5. x <- c(21, 62, 10,53)
  6. lbl <- c("London","New York","Singapore","Mumbai")
  7.  
  8. # Give the chart file a name.
  9. png(file = "3d_pie_chart.jpg")
  10.  
  11. # Plot the chart.
  12. pie3D(x,labels = lbl,explode = 0.1, main = "Pie Chart of Countries ")
  13.  
  14. # Save the file.
  15. dev.off()

当我们执行上面的代码,它产生以下结果 -

3D饼图
转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号