经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » R语言 » 查看文章
R语言条形图创建方法
来源:jb51  时间:2021/4/12 9:34:24  对本文有异议

条形图表示矩形条中的数据,条的长度与变量的值成比例。 R语言使用函数 barplot() 创建条形图。 R 语言可以在条形图中绘制垂直和水平条。 在条形图中,每个条可以给予不同的颜色。

语法

在 R 语言中创建条形图的基本语法是

  • H 是包含在条形图中使用的数值的向量或矩阵。
  • xlab 是 x 轴的标签。
  • ylab 是 y 轴的标签。
  • main 是条形图的标题。
  • names.arg 是在每个条下出现的名称的向量。
  • col 用于向图中的条形提供颜色。
  1. barplot(H, xlab, ylab, main, names.arg, col)

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

使用输入向量和每个条的名称创建一个简单的条形图。
以下脚本将创建并保存当前 R 语言工作目录中的条形图。

  1. # Create the data for the chart.
  2. H <- c(7,12,28,3,41)
  3.  
  4. # Give the chart file a name.
  5. png(file = "barchart.png")
  6.  
  7. # Plot the bar chart.
  8. barplot(H)
  9.  
  10. # Save the file.
  11. dev.off()

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

,使用R条形图

条形图标签,标题和颜色

可以通过添加更多参数来扩展条形图的功能。 主要参数用于添加标题。 col 参数用于向条形添加颜色。 name.args 是具有与输入向量相同数量的值的向量,以描述每个条的含义。

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

  1. # Create the data for the chart.
  2. H <- c(7,12,28,3,41)
  3. M <- c("Mar","Apr","May","Jun","Jul")
  4.  
  5. # Give the chart file a name.
  6. png(file = "barchart_months_revenue.png")
  7.  
  8. # Plot the bar chart.
  9. barplot(H,names.arg = M,xlab = "Month",ylab = "Revenue",col = "blue",
  10. main = "Revenue chart",border = "red")
  11.  
  12. # Save the file.
  13. dev.off()

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

条形图使用R型

组合条形图和堆积条形图

我们可以使用矩阵作为输入值,在每个条中创建条形图和堆叠组的条形图。
超过两个变量表示为用于创建组合条形图和堆叠条形图的矩阵。

  1. # Create the input vectors.
  2. colors <- c("green","orange","brown")
  3. months <- c("Mar","Apr","May","Jun","Jul")
  4. regions <- c("East","West","North")
  5.  
  6. # Create the matrix of the values.
  7. Values <- matrix(c(2,9,3,11,9,4,8,7,3,12,5,2,8,10,11),nrow = 3,ncol = 5,byrow = TRUE)
  8.  
  9. # Give the chart file a name.
  10. png(file = "barchart_stacked.png")
  11.  
  12. # Create the bar chart.
  13. barplot(Values,main = "total revenue",names.arg = months,xlab = "month",ylab = "revenue",
  14. col = colors)
  15.  
  16. # Add the legend to the chart.
  17. legend("topleft", regions, cex = 1.3, fill = colors)
  18.  
  19. # Save the file.
  20. dev.off()

,使用R堆叠条形图

到此这篇关于R语言条形图创建方法的文章就介绍到这了,更多相关R语言条形图内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持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号