Repository navigation
Expand file tree
/
Copy pathplot1.R
More file actions
48 lines (36 loc) · 1.8 KB
/
Copy pathplot1.R
File metadata and controls
48 lines (36 loc) · 1.8 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
######
# Plot 1 will depict a histogram of the Global Active Power variable in the
# Household Power Consumption dataset for the first 2 days in February of 2007.
######
# Load lubridate library for simpler date and time functions
library(lubridate);
# Data file
file <- "household_power_consumption.txt";
# Output file
plotFile <- "plot/plot1.png";
# Check for datafile in the current working directory
if(!file.exists(file)) stop(sprintf("Data file <%s> not found!", file));
# Read data file and set appropriate column classes
data <- read.table(file, header = TRUE, sep = ';', dec = '.', na.strings = '?',
colClasses = c("character", "character", "numeric",
"numeric", "numeric", "numeric", "numeric",
"numeric", "numeric"));
# Reformat Date and Time columns from character format to appropriate
# date and time formats using "ubridate" functions creating a new DateTime column.
data$DateTime <- as.POSIXct(paste(as.character(dmy(data$Date)), as.character(data$Time)))
# select data for 2/1/2007 through 2/2/2007 and remove NA rows
X <- na.omit(subset(data, year(DateTime) == 2007 & month(DateTime) == 2
& (day(DateTime) == 1 | day(DateTime) == 2)));
# Create the plot directory if needed
if(!file.exists("plot")) dir.create("plot", recursive = TRUE);
# initialize the PNG device
png(filename = plotFile, width = 480, height = 480);
# Create the histogram with appropriate labels, colors and margins
# depicting the power usages during the first 2 days in February of 2007.
with(X, {
par(mar=c(5.1, 4.1, 4.1, 2.1))
hist(Global_active_power, xlab = "Global Active Power (kilowatts)",
ylab = "Frequency", main = "Global Active Power", col = "red")
});
# Close the PNG device to save the file
dev.off();