Exercises

These excercises accompany the Plotting tutorial.

  1. Load the chicago_air dataset. Create a scatterplot of solar radiation (x-axis) vs ozone (y-axis) using base plotting functions in R.
  2. Create the same scatterplot, but adjust the color of the dots, the size of the dots (Hint: Use the cex command to adjust size), label the x and y-axis, and add a title. Use ?plot and ?par for help with plotting options and graphical parameters.
  3. Create the same plot, but only plot data from the months May - June (5-6). Using abline, add a horizontal line indicating where the ozone standard is. Save this plot to your thumb drive as a .png file.
  4. Using ggplot2 (geom_line), create a time series graph of the ozone data from chicago_air, where date = x, and ozone = y. Add x and y axis labels and a title to the plot. (Hint: Before you begin plotting you will need to convert the dates column in the chicago_air dataset to an R date for proper time-series plotting )
  5. Using ggplot2, create a scatterplot of solar radiation (x-axis) vs ozone (y-axis) data from the chicago_air dataset. Add a smooth trendline to the plot. Using an expression for the x axis label, express the units of solar radiation in W/m2. Finally, using the ggsave() function, save the plot to your thumb drive as a .png file.


Solutions


Solution 1

library(region5air)
data(chicago_air)
plot(x = chicago_air$solar, y = chicago_air$ozone)

Solution 2

plot(chicago_air$solar, chicago_air$ozone, 
     cex = 0.5, 
     col = "purple",
     xlab = "Solar Radiation (W/m2)", 
     ylab = "Ozone (ppm)", 
     main = "Solar Radiation vs Ozone at Chicago Monitor, 
     2013")

Solution 3

png("E:/RIntro/datasets/May_June_ozone.png")
summer.plot <- subset(chicago_air,month==5|month==6)
plot(summer.plot$solar, summer.plot$ozone, 
     cex = 0.5,
     col =  "purple"
     xlab = "Solar Radiation (W/m2)", 
     ylab = "Ozone (ppm)",
     main = "Solar Radiation vs Ozone at Chicago Monitor, 2013")
abline(h = .075, col = "red")

dev.off()

Solution 4

library(ggplot2)
chicago_air$date <- as.Date(chicago_air$date)  #Must first convert the dates so that they plot properly for the time-series graph.
p <- ggplot(chicago_air,aes(x = date, y = ozone))
p + geom_line() + 
  ylab("Ozone (ppm)") + 
  xlab("Date") + 
  ggtitle("Ozone time series, 2013")

Solution 5

library(ggplot2)

p <- ggplot(chicago_air,aes(x = solar, y = ozone))
p + geom_point() + geom_smooth(method = "lm") + ylab("Ozone (ppm)") +  xlab(expression('Solar Radiation W/m'^2)) + ggtitle("Solar Radiation vs Ozone, 2013")   

ggsave("E:/RIntro/datasets/solar_ozone.png")
## Saving 7 x 5 in image