首页 > 代码库 > R学习记录

R学习记录

1.在data.frame结构中,有时会有factor属性的值存在,不能直接使用as.numeric将factor中的数字直接转换,转换后的数据是错误的。一种方法是:使用as.character先将factor转换为character,再将character转换为numeric.

2.在R中设定横轴的时间刻度:

plot(x <- sort(rnorm(47)), type = "s", main = "plot(x, type = \"s\")", xaxt=‘n‘)
axis(1,c(0,10,20),c(‘01/10/23‘,‘10/12/06‘,‘11/03/18‘))

plot之后再使用axis增加,具体参考函数说明。


3.plot的说明,即legend,说明图中线的意义。

 

setwd("/Users/Yanyan/Documents/WorkDirectory/R Works/Coursera/Exploratory Analysis/Project 1")
data <- read.table(file="household_power_consumption.txt", header=TRUE, sep=";")
handle <- subset(data, (as.Date(data$Date,format=‘%d/%m/%Y‘) >= "2007-02-01") & (as.Date(data$Date,format=‘%d/%m/%Y‘) <= "2007-02-02"))

 

png(filename="plot4.png", width=480, height=480, units="px")
par(mfrow=c(2,2))
#Part 1
plot(as.numeric(as.character(handle$Global_active_power)),type="l",ylab="Global Active Power", xaxt=‘n‘,xlab="")
axis(1,c(0,length(handle$Global_active_power)/2,length(handle$Global_active_power)),c("Thu","Fri","Sat"))
##Part 2
plot(as.numeric(as.character(handle$Voltage)),type="l",ylab="Voltage", xaxt=‘n‘,xlab="datetime")
axis(1,c(0,length(handle$Global_active_power)/2,length(handle$Global_active_power)),c("Thu","Fri","Sat"))
##Part 3
plot(as.numeric(as.character(handle$Sub_metering_1)),type="l",xaxt=‘n‘,yaxt=‘n‘,xlab="",ylab="Energy sub metering")
lines(as.numeric(as.character(handle$Sub_metering_2)), type="l",col="red")
lines(handle$Sub_metering_3, type="l",col="blue")
axis(1,c(0,length(handle$Sub_metering_1)/2,length(handle$Sub_metering_1)),c("Thu","Fri","Sat"))
axis(side=2,at=seq(0,30,by=10))
legend("topright", legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),col=c("black","red","blue"),lwd=1,lty=c(1,1,1),pch=c(NA,NA,NA))
##Part 4
plot(as.numeric(as.character(handle$Global_reactive_power)),type="l",ylab="Global_reactive_power", xaxt=‘n‘,xlab="datetime")
axis(1,c(0,length(handle$Global_active_power)/2,length(handle$Global_active_power)),c("Thu","Fri","Sat"))

 

dev.off()

 

上述代码完全够了,不再赘述。

 参考自http://stackoverflow.com/questions/19053440/r-legend-with-points-and-lines-being-different-colors-for-the-same-legend-item

相关的:http://stackoverflow.com/questions/21868291/mixing-line-chart-and-dots-points-in-baseline-of-chart-in-r

http://www.statmethods.net/advgraphs/layout.html