-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot3.R
More file actions
52 lines (41 loc) · 1.87 KB
/
plot3.R
File metadata and controls
52 lines (41 loc) · 1.87 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
library("data.table")
## Change time locality to prevent label in Russian language
Sys.setlocale("LC_TIME", "C")
##
## Code for reading the data
##
firstRow <- rowNum <- NULL
readData <- function(sourceFilePath) {
## calculates index of rows for read
if (is.null(firstRow)) {
# takes only 2007-02-01 and 2007-02-02 measurements
allOccurrencesIndexes <- grep("^(1|2){1}/2/2007",readLines(sourceFilePath))
firstRow <<- allOccurrencesIndexes[1]
rowNum <<- length(allOccurrencesIndexes)
}
## reads only particular rows
householdEnergyUsage <- read.table(sourceFilePath, header = F, sep = ';', na.strings = "?", skip = firstRow-1,
nrows=rowNum, check.names = F, stringsAsFactors = F, quote='\"')
## setups meaningful column names
colNames <- c("Date", "Time", "Global_active_power", "Global_reactive_power", "Voltage", "Global_intensity",
"Sub_metering_1","Sub_metering_2", "Sub_metering_3")
setnames(householdEnergyUsage, names(householdEnergyUsage), colNames)
householdEnergyUsage$Date <- as.Date(householdEnergyUsage$Date, format = "%d/%m/%Y")
dateTime <- paste(householdEnergyUsage$Date, householdEnergyUsage$Time)
householdEnergyUsage$DateTime <- as.POSIXct(dateTime)
householdEnergyUsage
}
## Read data
householdEnergyUsage <- readData("data/household_power_consumption.txt")
## Reconstruct the plot 3
with(householdEnergyUsage, {
plot(Sub_metering_1~DateTime, type="l",
ylab="Energy sub metering", xlab="")
lines(Sub_metering_2~DateTime,col='Red')
lines(Sub_metering_3~DateTime,col='Blue')
})
legend("topright", col=c("black", "red", "blue"), lty=1, lwd=2,
legend=c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"))
## Save plot to a PNG file with a width of 480 pixels and a height of 480 pixels.
dev.copy(png, file = "plot3.png", height = 480, width = 480)
dev.off()