本文将讨论用R语言自带的基本绘图系统和ggplot2包来讨论基本图形的绘制。

一、条形图(bar chart):

我在学习这部分时会遇到这样的困惑,觉得条形图(bar chart)和直方图(histogram)差不多,两者都是用来统计频数的,histogram还可以用来统计频率。简单来说,条形图注重分类,而直方图更多用于绘制一系列有意义的连续型变量,具体例子见下文。Both charts display a summary value of a continuous variable that has been split into groups.

In bar charts, the groups are typically categorical variables.

In histograms the groups are typically intervals of another continuous variable.

# of people enrolled in each department of a college would suit a bar chart

# of people in each income quintile in your city would suit a histogram

One implication of this difference is that a natural order exists on the grouping axis of a histogram, but not a bar chart. In other words, it usually makes sense to sort a bar chart by value of the bar but a histogram should almost always remain sorted by the order of the groups. Using the examples above:

It would make sense to order the college departments from highest to lowest enrollment.

It wouldn't make as much sense to order the income quintiles by most to least people, you would end up with a counter-intuitive graph.

Bar charts usually have a space between the bars, histograms usually don't - reflecting the subtle differences in the relationships between adjacent groups.

—— Excerps from QUORA

见代码,这里使用vcd包里的Arthritis数据框作例子,先来看一下它里面有些啥:

> library(vcd)

载入需要的程辑包:grid

> head(Arthritis)

ID Treatment Sex Age Improved

1 57 Treated Male 27 Some

2 46 Treated Male 29 None

3 77 Treated Male 30 None

4 17 Treated Male 32 Marked

5 36 Treated Male 46 Marked

6 23 Treated Male 58 Marked

我想用统计Improved里的频数:

> library(ggplot2)

> ggplot(Arthritis,aes(x=Improved))+geom_bar()

barplot(height)比较笨,自己不会自动分组统计频数,你得算好了给它:

> counts

> counts

None Some Marked

42 14 28

> barplot(counts)

简单起见我不给labs(title, xlab等等)啦——咳咳,这个习惯不好,得改!:

顺便提一句,R自带的Plot不如ggplot2包里保存图形来的方便,ggplot()后的图形只要ggsave(file="blalalal")就ok了,这里介绍一下R里普通的Plot图形保存方法:To save a plot, you need to do the following:Open a device, usingpng(),bmp(),pdf()or similar

Plot your model

Close the device usingdev.off()

知乎的图片好像只支持jpg和png格式,所以我用的png,代码如下:

> png(file="d:/mybarplot.png")

> barplot(counts)

> dev.off()

也许你觉得颜色不好看,可以在barplot(counts, color = "yellow")设置亮瞎双眼,或者想要创新一下把图片横过来:barplot(counts, color = "yellow", horiz = TRUE),动动你的小手指吧~

barplot(height)里的height参数必须得是一个向量或者矩阵。上面给出的例子是向量的情况,如果height不是一个向量而是矩阵,则绘图结果将是一幅堆砌条形图或分组条形图(区别在于beside是否为TRUE):

> barplot(counts,col=c("red","yellow","green"),legend = rownames(counts))

> barplot(counts,col=c("red","yellow","green"),legend = rownames(counts), beside = TRUE)

二、直方图(histogram):

上代码:

> head(mtcars)

mpg cyl disp hp drat wt qsec vs am gear carb

Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4

Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4

Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1

Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1

Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2

Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1

> png(file = "d:/histo.png")

> layout(matrix(c(1,2,3,3),2,2,byrow = TRUE)

)

> hist(mtcars$mpg)

> hist(mtcars$mpg,breaks = 12, col="red", xlab = "Miles Per Gallon",main="Colored histograms with 12 bins")

> hist(mtcars$mpg,freq=FALSE,breaks =12)

> lines(density(mtcars$mpg),col = "lightblue",lwd = 2)

> dev.off()

breaks表示直方图的条数(bin),但R不一定听你的,你说几它显示不一定是几。譬如你要求breaks = 13, 它可能显示的是12,看看R的Documentary怎么说:breaks

one of:

a vector giving the breakpoints between histogram cells,

a function to compute the vector of breakpoints,

a single number giving the number of cells for the histogram,

a character string naming an algorithm to compute the number of cells (see ‘Details’),

a function to compute the number of cells.

In the last three cases the number is a suggestion only; the breakpoints will be set to pretty values. If breaks is a function, the x vector is supplied to it as the only argument.

人家说了,只当你给的是个参考而已、、、

上面也给出了定义breaks的五种方法,最好是用breaks = vector的形式,比如:

> se

> hist(height, breaks = se)

另外,值得注意的是,histogram当纵轴表示频率的时候可以和density函数一起用,因为他们用的坐标系是一样的。

用ggplot():

> ggplot(data = mtcars, aes(x= mpg))+geom_histogram(col ="black", fill =

"lightblue",bins = 12)+labs(title="Colored Histogram with 12 Bins")

bins的作用像hist()里面的breaks,不过这里的bins不再是建议。color表示的是bin的边框颜色,fill表示bin内部的颜色。

三、核密度图(density plot):

> plot(density(mtcars$mpg))

> polygon(density(mtcars$mpg),col = "lightgreen")

> rug(mtcars$mpg)

sm包中的sm.denstiy.compare()函数可以绘制多个核密度图用以比较:

> library(sm)

Package 'sm', version 2.2-5.4: type help(sm) for summary information

> attach(mtcars)

The following object is masked from package:ggplot2:

mpg

> str(mtcars)

'data.frame': 32 obs. of 11 variables:

$ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...

$ cyl : num 6 6 4 6 8 6 8 4 4 6 ...

$ disp: num 160 160 108 258 360 ...

$ hp : num 110 110 93 110 175 105 245 62 95 123 ...

$ drat: num 3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...

$ wt : num 2.62 2.88 2.32 3.21 3.44 ...

$ qsec: num 16.5 17 18.6 19.4 17 ...

$ vs : num 0 0 1 1 0 1 0 1 1 1 ...

$ am : num 1 1 1 0 0 0 0 0 0 0 ...

$ gear: num 4 4 4 3 3 3 3 4 4 4 ...

$ carb: num 4 4 1 1 2 1 4 2 2 4 ...

> lab

> lab

> lab

[1] "4 cylinder" "6 cylinder" "8 cylinder"

> cyl

> sm.density.compare(mpg,cyl)

> colfill

> legend("topright",levels(cyl),fill= colfill)

ggplot()就能用分组来比较不同水平的核密度图:

> library(ggplot2)

> ggplot(data = mtcars, aes(x=mpg,col = cyl))+geom_density()+geom_rug()

可以看到虽然数据是一模一样的,但两者画出来的图形确实有差别的,应该是计算方式有差异。加上地毯图帮助理解。

四、箱线图(boxplot):

箱线图可以展示单个变量或分组变量,使用格式为:

boxplot(formula, data= dataframe)

> boxplot(mpg~cyl, data=mtcars,notch = TRUE,varwidth = TRUE,col = "lightblue",xlab = "cylinder",ylab = "mpg")

boxplot可以自动分组,其中varwidth=TRUE使箱线图的宽度与样本大小成正比。

一个箱线图一共有五条水平的线,从上到下分别表示最大值,上四分位数,中位数,下四分位数和最小值。cylinder=8的箱线图底下有个点表示离群点。

用ggplot():

> ggplot(data = mtcars, aes(x=cyl,y=mpg))+geom_boxplot(fill= "lightblue")

两者几乎是相同的。

交叉因子的箱线图:

> boxplot(mpg~am*cyl, data=mtcars,main = "MPG Distribution by AutoType",xlab = "Auto Type",ylab = "mpg",col = c("green","darkgreen"))

五、点图(dotchart):

> dotchart(mtcars$mpg, labels = row.names(mtcars),main = "Gas Mileage for Car Models",xlab= "mpg")

> ggplot(data=mtcars, aes(x=mpg,y=row.names(mtcars)))+geom_point()+labs(title="Gas Mileage for Car Models")

r语言 图形一览_R语言之图形概览相关推荐

  1. r语言 图形一览_R语言实战—图形篇(图形初阶)

    最近沉迷学习R语言,不得不说<R语言实战>真的太详细了,详细的阅读完这本书后,我的收获不小.为了方便自己复习,将这本书的内容整理归纳为两个部分:统计篇(数据分析)和图形篇(数据可视化). ...

  2. r语言 图形一览_R语言常见图形(1)

    本文涉及的基础图形有条形图.饼图.直方图.核密度图.箱线图.点图. 条形图 条形图通过垂直或水平的条形展示类别变量的分布(频数). 函数barplot() 调用格式: barplot(height) ...

  3. r语言 图形一览_R语言统计与绘图:ggplot2图形组合布局

    在科研论文中,有时我们需要绘制几张图形,并将这几张图形整合到一张大图上面. 前面我们学习了基础绘图包怎么组合布局图形,今天来学习两个新函数,看ggplot2绘制的图形怎么组合. ggplot2组合图形 ...

  4. r语言 图形一览_R语言实战(第2版):第三章 图形初阶(01)

    注:如果在头条里面的代码不清楚,可以在""简书""中搜索"康华同学",同步更新!!! 3.1 使用图形 R是一个惊艳的图形构建平台.这里我特 ...

  5. r语言清除变量_R语言(1)初识与数据结构

    点击上方蓝字,记得关注我们! a picture is worth a thousand words! 一,R语言简介 1,R语言的发展 上世纪90年代初,新西兰奥克兰大学 Ross Ihaka 和 ...

  6. r语言electricity数据集_R语言实战学习

    <R语言实战>中文电子版 提取码:lx35 已经学习打卡R语言22天了,可以说是初窥真容--基本了解R的数据和函数:作为程序语言,就是要多练习,多领悟,在实战中发现问题并解决问题. 所以, ...

  7. r - 求平均成绩_R语言 从零开始的笔记(一)

    R是用于统计分析.绘图的语言和操作环境.R是属于GNU系统的一个自由.免费.源代码开放的软件,它是一个用于统计计算和统计制图的优秀工具. R语言于生物学分析中的应用越来越广泛,在其他领域的统计绘图应用 ...

  8. r语言mfrow全程_R语言(绘图入门)

    原文链接:https://wklchris.github.io/R-plotting-basic.html R 的绘图功能一直为业内所津津乐道.用了 Python 的 matplolibt 和 R 的 ...

  9. R语言JAVA对比_R语言统计分析应用与SAS、SPSS的比较

    能够用来做统计分析的软件和程序很多,目前应用比较广泛的包括:SPSS, SAS.R语言,Matlab,S-PLUS,S-Miner等.下面我们来看一下各应用的特点: SPSS: 最简单的,都是菜单操作 ...

最新文章

  1. 第十六届全国大学生智能车竞赛全国总决赛获奖排行榜
  2. 在Java中使用Spliterator
  3. python 使用UUID库生成唯一ID
  4. SVM+HOG:从完全不包含人体的图片中随机剪裁出64*128大小的用于人体检测的负样本
  5. python面试题_春招苦短,我用百道Python面试题备战
  6. Mac配置Java环境变量等
  7. linux剪贴板复制文件原理,linux剪贴板原理
  8. 点击按钮创建一个表格 点击按钮创建一个表格 权限选择 元素的value属性操作
  9. Orbeon form 的安装和使用教程
  10. document.getElementsByName 标准
  11. python 数字类型和字符串类型的相互转换_python 数字类型和字符串类型的相互转换...
  12. 支付宝招“找茬”程序员,年薪无上限;谷歌宣布实现“量子霸权”;node.js 13.0.3 发布 | 极客头条...
  13. java语言包安装_Eclipse 多国语言包的安装以及插件的安装方法
  14. 【java】PageHelper.startPage
  15. vue解决Not allowed to load local resource
  16. 玩物得志:效率为王!如何构建大数据平台?
  17. 腾讯发布 2017 年度代码报告
  18. CityEngine学习资料——split分割
  19. Java线程池的四种创建方式
  20. C#简单音乐播放器(三)

热门文章

  1. c++生成nurbs曲面文件_使用曲面细分丰富原始多边形
  2. Livox 开源分享:关于激光雷达去畸变的那些事儿
  3. Kaggle竞赛中使用YoloV5将物体检测的性能翻倍的心路历程
  4. 汇总|目标检测中的数据增强、backbone、head、neck、损失函数
  5. INQ渐进量化方法详解
  6. RDKit toolkit实战一:调用Python API
  7. 第三十三课.一些经典的优化策略与神经网络变种
  8. 附录6:TensorFlow基础(二)
  9. python中的下划线_Python中的下划线详解
  10. 生信服务器 | Linux 时间戳和标准时间