-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplot2.R.txt
64 lines (52 loc) · 2.1 KB
/
plot2.R.txt
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
library(data.table)
library(ggplot2)
#LoadData : Load NEI and SCC data into global variables if not already present.
# These variables are then accessed by plot functions.
# NEI and SCC are loaded as data.table class.
# If data files do not exist locally then they are downloaded
# and unzipped.
LoadData <- function() {
if (!file.exists("summarySCC_PM25.rds") ||
!file.exists("Source_Classification_Code.rds")) {
if (!file.exists("FNEI_data.zip")) {
print("Downloading FNEI_data.zip ...")
download.file("https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2FNEI_data.zip",
"FNEI_data.zip", mode="wb")
unzip("FNEI_data.zip")
}
}
#Note: NEI and SCC are set in global environment
if (!exists("NEI")) {
print("Loading NEI data ...")
NEI <<- as.data.table(readRDS("summarySCC_PM25.rds"))
}
if (!exists("SCC")) {
print("Loading SCC data ...")
SCC <<- as.data.table(readRDS("Source_Classification_Code.rds"))
}
}
#plot2: Plot a graph showing total PM 2.5 emissions
# of the Baltimore City, Maryland
plot2 <- function() {
LoadData() #NEI is now in global environment
#get the sum of emissions by year for Baltimore City (fips=24510)
nei <- NEI[fips == "24510", sum(Emissions), by=year]
setnames(nei, 2, "total.emissions")
#plot the data
plot(nei$year, nei$total.emissions,
type="b", yaxt="n", xaxt="n", pch=20,
xlab="Year", ylab="Emissions (in thousand tons)",
main="Total PM 2.5 emissions of Baltimore City, MD")
round.by <- 1000
axis(2, at=1:4 * round.by, labels=format(as.double(1:4), nsmall=1))
axis(1, at=nei$year, labels=nei$year)
text(nei$year, nei$total.emissions,
round(nei$total.emissions/round.by, 2),
cex=0.6, pos=c(4,2,4,2))
#save the plot to png
dev.copy(png, file="plot2.png")
dev.off()
#return data to caller
nei
}
plot2()