forked from rdpeng/ExData_Plotting1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplot1.R
47 lines (39 loc) · 2.24 KB
/
plot1.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
########################################################################################
##
## 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.
##
########################################################################################
plot1 <- 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",]
## Set PNG graphics device and create output file
png("plot1.png", width = 480, height = 480, units = "px")
## Plot histogram of household global active power in kilowatts
hist(as.numeric(data$Global_active_power),
main = "Global Active Power", ## set the main title of the plot
xlab = "Global Actvie Power (kilowatts)", ## set the label for x-axis
col = "red") ## set the color to fill the bars
## Close graphics device
dev.off()
}