forked from rdpeng/ExData_Plotting1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplot3.R
38 lines (33 loc) · 1.69 KB
/
plot3.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
###Code to use for subsetting data for plot generation
###Assumes data file is in current working directory
#read some rows to determine class type for each column
first5rows <- read.table("household_power_consumption.txt", header = TRUE, sep = ";", nrows = 5, na.strings = "?")
classes <- sapply(first5rows, class)
#read in all the data using the identified classes
alldata <- read.table("household_power_consumption.txt", header = TRUE, colClasses = classes, sep = ";", nrows = 210000, na.strings = "?")
#convert Date column to Date data class
alldata$Date <- as.Date(alldata$Date, format = '%d/%m/%Y')
min = as.Date("2007-01-31")
max = as.Date("2007-02-03")
#extract the subset of data we want to work with
data <- subset(alldata, Date > min & Date < max)
#remove the larger data set to conserve memory
rm(alldata)
#merge data and time columns to form datetime information
data$datetime <- paste(as.character(data$Date), data$Time, sep = ' ')
#convert datetime from char to date class
data$datetime <- strptime(data$datetime, format='%Y-%m-%d %H:%M:%S')
png(file = "plot3.png", width = 480, height = 480)
#plot the points for Sub_metering_1
with(data, plot(datetime, Sub_metering_1, pch = '.', ylab ="Energy sub metering", xlab = "" ))
#overlay the line for Sub_metering_1
with(data, lines(datetime, Sub_metering_1))
#overlay the line for Sub_metering_2
with(data, lines(datetime, Sub_metering_2, col = 'red'))
#overlay the line for Sub_metering_3
with(data, lines(datetime, Sub_metering_3, col = "blue"))
#create legend for chart, matching lines names to their colors
legend( x="topright",
legend=c("Sub_metering_1","Sub_metering_2", "Sub_metering_3"),
col=c("black", "red", "blue"), lty=c(1,1,1))
dev.off()