forked from rdpeng/ExData_Plotting1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplot2.R
49 lines (40 loc) · 2.4 KB
/
plot2.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
39
40
41
42
43
44
45
46
47
48
49
########################################################################################
##
## To perform analysis for this assignment, it is necessary to download dataset from URL:
## https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip
##
## The code below checks if the necessary data file exists in the working directory. If not,
## it will be downloaded from the web and unzipped to your working directory.
##
## If you want to prevent downloading, make sure that you retrieve and copy a file named
## "household_power_consumption.txt" to the working directory.
##
########################################################################################
plot2 <- function() {
## Load data.table package needed in order to use 'fread' function for fast file reading
## If it isn't installed, install the data.table package with install.packages()
library(data.table)
## Set the name of data file
file <- "household_power_consumption.txt"
## Check if the file exists in the working directory. If not, retrieve it from the web
if (!file.exists(file)) {
fileURL <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
download.file(fileURL, "data.zip", method = "curl")
unzip("data.zip")
}
## 'fread' function does the same as 'read.table', but faster.
## Here it reads a file in table format where all variables are read in as characters
alldata <- fread(file, header = TRUE, sep = ";", na.strings = "?", colClasses = "character")
## Subset data to the required dates for analysis
data <- alldata[alldata$Date == "1/2/2007" | alldata$Date == "2/2/2007",]
## Create a POSIXlt/POSIXct class vector of the concatenated values of Date and Time character vectors
datetime <- strptime(paste(data$Date, data$Time), format = "%d/%m/%Y %H:%M:%S")
## Set PNG graphics device and create output file
png("plot2.png", width = 480, height = 480, units = "px")
plot(datetime, as.numeric(data$Global_active_power),
type = "l", ## set the type of plot ("l" for lines)
xlab = "", ## set the label for x-axis (empty as in the reference plot)
ylab = "Global Active Power (kilowatts)") ## set the label for y-axis
## Close graphics device
dev.off()
}