forked from rdpeng/ExData_Plotting1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot4.r
More file actions
90 lines (71 loc) · 2.35 KB
/
plot4.r
File metadata and controls
90 lines (71 loc) · 2.35 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# Function for loading a smaller interval from a dataset in a CSV.
# The csv must contain columns "Date" and "Time"
# in the following format: %d/%m/%Y and %H:%M:%S
loadIntervalCSV <- function (pathToCsv, firstDay, nDays = 1) {
# Load first row
firstRow <- read.csv(pathToCsv, sep=";", nrows=1)
# Epoch of the first record
epochFirstRow <- as.integer(
as.POSIXct(paste(firstRow$Date, firstRow$Time), format="%d/%m/%Y %H:%M:%S")
)
# Epoch of the first minute of a given day
epochStart <- as.integer(
as.POSIXct(paste(firstDay, "00:00:00"), format="%d/%m/%Y %H:%M:%S")
)
# Number of minutes between of the first record to be read i.e. rows to skip
skipRows = (epochStart - epochFirstRow) / 60
# Number of minutes in n days
minutes2days = 24 * 60 * nDays
# Load data
dataSet <- read.csv("household_power_consumption.txt", sep=";",
skip=skipRows, nrows=minutes2days)
# Set colnames in dataSet
colnames(dataSet) <- colnames(firstRow)
return(dataSet)
}
# Load 2007-02-01 and 2007-02-02
dataSet <- loadIntervalCSV("household_power_consumption.txt", "01/02/2007", nDays = 2)
# Start device
png(file = "plot4.png")
# Adjust Locale
#Sys.setlocale("LC_TIME", "en_US.utf8")
# Creates a Datetime column in dataset
dataSet$Datetime = as.POSIXct(paste(dataSet$Date, dataSet$Time),
format = "%d/%m/%Y %H:%M:%S"))
# Let plot region to allow 4 graphs and set bg color
par(mfcol = c(2,2), bg = "transparent")
# Plot top-left
with(dataSet,
# Draw plot 1
plot(Global_active_power ~ Datetime, type="l", xlab="",
ylab="Global Active Power")
)
# Plot bottom-left
with(dataSet, {
plot(Sub_metering_1 ~ Datetime,
ylab = "Energy sub metering",
xlab = "",
type = "l",
col = "black")
lines(Sub_metering_2 ~ Datetime, col = "red")
lines(Sub_metering_3 ~ Datetime, col = "blue")
legend("topright", lty = "solid", col = c("black", "red", "blue"),
legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"),
box.lwd = 0)
})
# Plot top-right
with(dataSet, {
plot(Voltage ~ Datetime,
ylab="Voltage",
xlab="datetime",
type="l")
})
# Plot bottom-right
with(dataSet, {
plot(Global_reactive_power ~ Datetime,
ylab="Global_reactive_power",
xlab="datetime",
type="l")
})
# Close the device
dev.off()