R语言学习笔记——Base Graphics

做exploratory data annalysis的作业,差点被虐死了,R从头开始,边做边学,最后搞到一点多才弄完,还有一个图怎么画都不对,最后发现是数据读取的时候有问题。

用来画图的数据来自:http://archive.ics.uci.edu/ml/datasets/Individual+household+electric+power+consumption

数据属性如下:

Attribute Information:

1.date: Date in format dd/mm/yyyy 
2.time: time in format hh:mm:ss 
3.global_active_power: household global minute-averaged active power (in kilowatt) 
4.global_reactive_power: household global minute-averaged reactive power (in kilowatt) 
5.voltage: minute-averaged voltage (in volt) 
6.global_intensity: household global minute-averaged current intensity (in ampere) 
7.sub_metering_1: energy sub-metering No. 1 (in watt-hour of active energy). It corresponds to the kitchen, containing mainly a dishwasher, an oven and a microwave (hot plates are not electric but gas powered). 
8.sub_metering_2: energy sub-metering No. 2 (in watt-hour of active energy). It corresponds to the laundry room, containing a washing-machine, a tumble-drier, a refrigerator and a light. 
9.sub_metering_3: energy sub-metering No. 3 (in watt-hour of active energy). It corresponds to an electric water-heater and an air-conditioner.

1.读取数据:

   在R中,要从txt读取数据,需要使用read.table函数,它的几个常用的参数列表如下:

参数含义
file文件的名字,可以用文件的绝对路径
header逻辑值,为1表示文件第一行包含各个变量的名称,如果不包含,可以用colnames参数指定
sep各个变量之间的分隔符,可能是空格,分号,逗号等等,根据文件自定义就可以了
col.names是一个向量,指定每一列的名称
colClasses是一个类向量,指定每一列的类别
na.strings表明数据中什么样的值被定义为NA

 

 

 

 

 

 

本例中用如下代码读入数据:

x<-read.table("D:/coursera/data analysis/household_power_consumption.txt",sep=";", header=T, colClasses = c('character', 'character', 'numeric',
                                    'numeric', 'numeric', 'numeric','numeric', 'numeric', 'numeric'),na.strings='?')

2. 合并年月日和时分秒,并把它们转换成Date类型存放到新增加的一列DateTime中

   上述代码中是将年月日和时分秒按照character类型读入的,接下来的运算中使用Date类型会比较方便。

   主要有两个步骤:1.利用paste函数拼接年月日和时分秒;2.将拼接后的串转换成Date型。

   代码如下: 

x$DateTime <- strptime(paste(x$Date, x$Time),"%d/%m/%Y %H:%M:%S")

   这里,strptime把粘贴Date和Time得到的串转换成Date格式,其中第二个参数format非常重要,原来的数据形如16/12/2006 17:24:00,所以format中的"%d/%m/%Y %H:%M:%S"要和数据一一对应。比如这里用了Y而不是y,原因在于Y表示带世纪的年份,而y只能表示不带实际的年份,它的取值范围只有00~99。还有数据中用于分隔的“/”和":"都不能省略,一旦格式和数据不同,就会发现转换后的数据都变成NA。strptime中format常用的几个参数列出如下:

%dday(01~31)
%mmonth(01~12)
%YYear with century(0~9999)
%yYear without century(00~99)
%Hhour(00~23)
%Mminutes(00~59)
%Ssecond(00~61)

 

   

 

 

 

(ps.我也不知道为什么%S可以到61,帮助文档里面是这么写的=。=)

转换后DateTime值形如:2006-12-16 17:24:00

3.抽取日期范围在“2007-2-1”和“2007-2-2”之间(包括边界)的数据放入s中:

s <- subset(x,as.Date(DateTime) >= as.Date("2007-02-01")&as.Date(DateTime) <= as.Date("2007-02-02"))

这里主要用到as.Date()函数,它把一个串转换为Date格式。

4.直方图

  这里主要以global_active_power频度直方图为例,代码如下:

hist(s$Global_active_power,freq=TRUE,col="red",xlab="Global Active Power(kilowatts)",ylab="Frequency",xaxt="n",yaxt="n",main="Global Active Power")
axis(side=2,at=seq(0,1200,200))
axis(side=1,at=NULL)

hist函数有多个参数,可以在帮助文档中查看,常用的几个列举如下:

pch图例样式,默认为空心的小圆圈
col颜色,用整数定义,可以用colors()函数查看所有的颜色(查了一下,居然有657种=。=)
xlabx轴标签
ylaby轴标签
main图像名称

  

 

 

 

 

上述的参数中还设置了xaxt="n",yaxt="n",是为了之后用axis(side=2,at=seq(0,1200,200))和axis(side=1,at=NULL)分别标注x和y轴的刻度。其中的seq(0,1200,200)表示产生一个0~1200,以200为公差的等差序列。

5.把图像存为png格式

 

dev.copy(png,filename="plot1.png",height=480, width=480,bg="white")
dev.off()

 

这里会把图像存放在当前路径下,可以用getwd()查看当前路径。

生成的图像如下:

6. 折线图

    这里以DateTime-global_active_power折线图为例,有两种画图方式

    5.1 直接用plot:        

plot(s$DateTime, s$Global_active_power, xlab="n", ylab="Global Active Power(kilowatt)", type="l",lty=1)

    5.2 用plot和lines函数:      

plot(s$DateTime, s$Global_active_power, xlab="n", ylab="Global Active Power(kilowatt)", pch=NA)
lines(x$DateTime, x$Global_active_power)

     先用pch=NA画出一张空白图,然后用lines在上面增加折线。

     第二种方法的时间会比第一种的慢。

     画出的图形如下:

     

7. 在一张图中画出多条折线并增加图例

   上述的第二种方法只要多加几个lines()函数就可以实现这一功能了。这里以DateTime-sub_metering_*(*=1,2,3)为例:

plot(s$DateTime, s$Sub_metering_1, yaxt="n", ylab="Energy Sub metering",type="l")
lines(s$DateTime, s$Sub_metering_2, col="red")
lines(s$DateTime, s$Sub_metering_3, col="blue")

   增加图例用legend()函数:   

legend("topright",legend=c("sub_metering_1","sub_metering_2","sub_metering_3"),col=c("black","red","blue"),cex=0.8)

   其中legend=c("sub_metering_1","sub_metering_2","sub_metering_3")规定三个图例的名称,col=c("black","red","blue")规定三个图例的颜色,cex=0.8规定图例大小

  整体折线图如下:

8. 在一张图上画多个小图。 

   使用par函数设置一幅图的整体特征就可以做到这一点。par()函数常用的参数列表如下: 

las取值在{0,1,2,3}中,规定轴标签的位置,比如与坐标轴平行,垂直等等
bg背景颜色
mar边缘大小,一般用mar=c(1,2,3,4)制定,1,2,3,4对应的数字分别制定下,左,上,右的边缘大小
oma图外部的边缘大小,默认为0
mfrow每行图的数量
mfcol每列图的数量

 

 

 

 

 

上述有一点关于mfrow和mfcol的区别,通过使用mfrow(2,2)和mfcol(2,2)我们都可以得到2*2张子图,二者的区别在于作图的顺序不同,mfrow(2,2)通过左上->右上->左下->右下顺序作图,而mfcol(2,2)通过左上->左下->右上->右下的方式作图,虽然不知道这种区别有什么用,先放在这里了。

如上表所示,如果我们改变mfrow和mfcol的数值就可以在一幅图上画出mfrow*mfcol张小图,代码如下:

par(oma=c(0,0,0,0),mfrow=c(2,2),mar=c(4,4,2,2))

把上述三幅图加上另外一幅图一共四幅图画在一张图上:

 1 #读入数据
 2 x<-read.table("D:/coursera/data analysis/household_power_consumption.txt",sep=";", header=T, colClasses = c('character', 'character', 'numeric','numeric', 'numeric', 'numeric','numeric', 'numeric', 'numeric'),na.strings='?')
 3 
 4 #整个图中画2*2幅小图
 5 par(oma=c(0,0,0,0),mfrow=c(2,2),mar=c(4,4,2,2))
 6 
 7 #处理时间
 8 x$DateTime <- strptime(paste(x$Date, x$Time),"%d/%m/%Y %H:%M:%S")                                                                                                            
 9 s <- subset(x,as.Date(DateTime) >= as.Date("2007-02-01")&as.Date(DateTime) <= as.Date("2007-02-02"))
10 s$Time <- strptime(s$Time,"%Y-%m-%d %H:%M:%S")
11 
12 #第一张图
13 hist(s$Global_active_power,freq=TRUE,col="red",xlab="Global Active Power(kilowatts)",ylab="Frequency",xaxt="n",yaxt="n",main="Global Active Power")
14 axis(side=2,at=seq(0,1200,200))
15 axis(side=1,at=NULL)
16 
17 #第二张图
18 plot(s$DateTime, s$Global_active_power, xlab="n", ylab="Global Active Power(kilowatt)", type="l",lty=1)
19 axis(side=2,at=seq(0,6,2))
20 
21 #第三张图
22 plot(s$DateTime, s$Sub_metering_1, yaxt="n", ylab="Energy Sub metering",type="l")
23 lines(s$DateTime, s$Sub_metering_2, col="red")
24 lines(s$DateTime, s$Sub_metering_3, col="blue")
25 axis(side=2,at=seq(0,30,10))
26 legend("topright",legend=c("sub_metering_1","sub_metering_2","sub_metering_3"),col=c("black","red","blue"),cex=0.8)
27 
28 #第四章图
29 plot(s$DateTime, as.numeric(s$Global_reactive_power),xlab="datetime", ylab="Global reactive power", type="h",lty=1)
30 axis(side=2,at=seq(0.0,0.5,0.1))
31 dev.copy(png,filename="plot4.png",height=480, width=480,bg="white")
32 dev.off()

图形如下:

转载于:https://www.cnblogs.com/sunshineatnoon/p/3725993.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值