forked from rdpeng/ExData_Plotting1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplot1.R
26 lines (22 loc) · 1.23 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
# Load the data
powerData <- read.table("household_power_consumption.txt", header = TRUE, sep = ";", na.strings = "?")
# Convert the Date and Time variables to a single Date_Time variable
powerData$Date_Time <- as.POSIXct(paste(powerData$Date, powerData$Time), format = "%d/%m/%Y %H:%M:%S")
# Subset the data to the specified date range
startDateTime <- as.POSIXct("2007-02-01 00:00:00")
endDateTime <- as.POSIXct("2007-02-02 23:59:59")
subsetData <- powerData[powerData$Date_Time >= startDateTime & powerData$Date_Time <= endDateTime, ]
# Replace infinite values with NA and remove them
subsetData$Global_active_power[is.infinite(subsetData$Global_active_power)] <- NA
subsetData <- na.omit(subsetData)
# Create the plot
png("plot1.png", width = 480, height = 480)
hist(subsetData$Global_active_power, breaks = 30, col = "red", main = "Global Active Power (kilowatts) vs Frequency", xlab = "Global Active Power (kilowatts)", ylab = "Frequency")
# Check if the plot is empty
if(length(subsetData$Global_active_power[!is.na(subsetData$Global_active_power)]) == 0) {
# If the plot is empty, print a message
message("Plot is empty")
} else {
# If the plot is not empty, save it to a PNG file and close the device
dev.off()
}