Load library tidyverse in order to access dplyr and ggplot2
library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr 1.1.4 ✔ readr 2.1.5
✔ forcats 1.0.0 ✔ stringr 1.5.1
✔ ggplot2 3.5.1 ✔ tibble 3.2.1
✔ lubridate 1.9.4 ✔ tidyr 1.3.1
✔ purrr 1.0.2
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag() masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
The source for this dataset is the New York State Department of Conservation and the National Weather Service of 1973 for five months from May to September recorded daily.
Load the Dataset into your Global Environment
Because airquality is a pre-built dataset, we can write it to our data directory to store it for later use.
data("airquality")
Look at the Structure of the Data
In the global environment, click on the row with the airquality dataset and it will take you to a “spreadsheet” view of the data.
View the Data Using the “Head” Function
The function, head, will only disply the first 6 rows of the dataset. Notice in the global environment to the right, there are 153 observations (rows)
Notice that all the variables are classified as either integers or continuous values.
Calculate Summary Statistics
If you want to look at specific statistics, here are some variations on coding. Here are 2 different ways to calculate “mean.”
mean(airquality$Temp)
[1] 77.88235
mean(airquality[,4])
[1] 77.88235
For the second way to calculate the mean, the matrix [row,column] is looking for column #4, which is the Temp column and we use all rows.
Calculate Median, Standard Deviation, and Variance
median(airquality$Temp)
[1] 79
sd(airquality$Wind)
[1] 3.523001
var(airquality$Wind)
[1] 12.41154
Rename the Months from Number to Names
Sometimes we prefer the months to be numerical, but here, we need them as the month names. There are MANY ways to do this. Here is one way to convert numbers 5 - 9 to May through September.
See how Month has changed to have characters instead of numbers (it is now classified as “character” rather than “integer”)
summary(airquality$Month)
Min. 1st Qu. Median Mean 3rd Qu. Max.
5.000 6.000 7.000 6.993 8.000 9.000
Month is a Categorical Variable with Different Levels, Called Factors
This is one way to reorder the Months so they do not default to alphabetical (you will see another way to reorder DIRECTLY in the chunk that creates the plot below in Plot #1.
Here is a first attempt at viewing a histogram of temperature by the months May through September. We will see that temperatures increase over these months. The median temperature appears to be about 75 degrees.
fill = Month colors the histogram by months between May - Sept.
scale_fill_discrete(name = “Month”…) provides the month names on the right side as a legend in chronological order. This is a different way to order than what was shown above.
labs allows us to add a title, axes labels, and a caption for the data source.
p1 <- airquality |>ggplot(aes(x=Temp, fill=Month)) +geom_histogram(position="identity")+scale_fill_discrete(name ="Month", labels =c("May", "June","July", "August", "September")) +labs(x ="Monthly Temperatures from May - Sept", y ="Frequency of Temps",title ="Histogram of Monthly Temperatures from May - Sept, 1973",caption ="New York State Department of Conservation and the National Weather Service") #provide the data sourcep1
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
Warning: The following aesthetics were dropped during statistical transformation: fill.
ℹ This can happen when ggplot fails to infer the correct grouping structure in
the data.
ℹ Did you forget to specify a `group` aesthetic or to convert a numerical
variable into a factor?
Plot 1 Output
Is this plot useful in answering questions about monthly temperature values?
Plot 2: Improve the Histogram of Average Temperature by Month
Outline the bars in white using the color = “white” command
Use alpha to add some transparency (values between 0 and 1)
Change the binwidth
Add some transparency and white borders around the histogram bars.
Plot 2 Code
p2 <- airquality |>ggplot(aes(x=Temp, fill=Month)) +geom_histogram(position="identity", alpha=0.5, binwidth =5, color ="white")+scale_fill_discrete(name ="Month", labels =c("May", "June","July", "August", "September")) +labs(x ="Monthly Temperatures from May - Sept", y ="Frequency of Temps",title ="Histogram of Monthly Temperatures from May - Sept, 1973",caption ="New York State Department of Conservation and the National Weather Service")p2
Warning: The following aesthetics were dropped during statistical transformation: fill.
ℹ This can happen when ggplot fails to infer the correct grouping structure in
the data.
ℹ Did you forget to specify a `group` aesthetic or to convert a numerical
variable into a factor?
Plot 2 Output
Here July stands out for having high frequency of 85 degree temperatures. The dark purple color indicates overlaps of months due to the transparency.
Did this improve the readability of the plot?
Plot 3: Create Side-by-side Boxplots Categorized by Month
We can see that August has the highest temperatures based on the boxplot distribution.
p3 <- airquality |>ggplot(aes(Month, Temp, fill = Month)) +labs(x ="Months from May through September", y ="Temperatures", title ="Side-by-Side Boxplot of Monthly Temperatures",caption ="New York State Department of Conservation and the National Weather Service") +geom_boxplot() +scale_fill_discrete(name ="Month", labels =c("May", "June","July", "August", "September"))p3
Warning: Continuous x aesthetic
ℹ did you forget `aes(group = ...)`?
Warning: The following aesthetics were dropped during statistical transformation: fill.
ℹ This can happen when ggplot fails to infer the correct grouping structure in
the data.
ℹ Did you forget to specify a `group` aesthetic or to convert a numerical
variable into a factor?
Plot 3
Notice that the points above and below the boxplots in June and July are outliers.
Plot 4: Side by Side Boxplots in Gray Scale
Make the same side-by-side boxplots, but in grey-scale.
Use the scale_fill_grey command for the grey-scale legend, and again, use fill=Month in the aesthetics.
Plot 4 Code
p4 <- airquality |>ggplot(aes(Month, Temp, fill = Month)) +labs(x ="Monthly Temperatures", y ="Temperatures", title ="Side-by-Side Boxplot of Monthly Temperatures",caption ="New York State Department of Conservation and the National Weather Service") +geom_boxplot()+scale_fill_grey(name ="Month", labels =c("May", "June","July", "August", "September"))p4
Warning: Continuous x aesthetic
ℹ did you forget `aes(group = ...)`?
Warning: The following aesthetics were dropped during statistical transformation: fill.
ℹ This can happen when ggplot fails to infer the correct grouping structure in
the data.
ℹ Did you forget to specify a `group` aesthetic or to convert a numerical
variable into a factor?
Plot 4
Here we just changed the color palette to gray scale using scale_fill_grey.
Plot 5: Now Make One Plot on Your Own of Any of the Variables in This Dataset. It May be a Scatterplot, Histogram, or Boxplot.
p5 <- airquality %>%ggplot(mapping =aes(x = Solar.R, y = Ozone, color = Solar.R)) +geom_point(na.rm =TRUE) +scale_color_gradient(low ="#ADDAFF", high ="#0064B7", name ="Solar Radiation") +labs(x ="Solar Radiation",y ="Ozone Concentration",title ="Scatterplot of Ozone Concentration by Solar Radiation",caption ="New York State Conservation and the National Weather Service")p5
solar_radiation <- airquality$Solar.Rozone_concentration <- airquality$Ozonecorrelation <-cor(solar_radiation, ozone_concentration, use ="complete.obs")print(correlation)
Describe any special code you used to make this plot
Essay
The plot I created is a scatterplot that depicts the relationship between solar radiation and ozone concentration using the airquality dataset. Each point represents an observation pulled from the data set matched to its solar radiation and ozone concentration values, with lower values of solar radiation appearing in light blue and higher values of solar radiation appearing in dark blue. Solar radiation is the independent variable and ozone concentration is the dependent variable. The plot reveals a weak positive correlation of r = 0.3 and an extremely statistically significant p-value of p = 0.0001. This supports my hypothesis that ozone concentration would increase with solar radiation and that ozone concentration and solar radiation have a direct relationship rather than a spurious one. This is because the UV radiation in sunlight reacts with nitrogen oxides and volatile organic compounds to create ozone, leading to higher concentrations of tropospheric ozone under more sunlight. Here is an explanation of my codes:
Code 1 for Plot 5 - Scatterplot
Line 1: p5 <- airquality
Explanation: p5 acts as “storage” for the code, while the arrow (<-) puts the code inside it. The piping (%>%) passes the data from the airquality data set (airquality) onto the next function.
Line 2: ggplot(mapping = aes(x = Solar.R, y = Ozone, color = Solar.R)) +
Explanation: ggplot creates the plot, and mapping = aes() sets up the plot’s aesthetics. Sx = Solar.R and y = Ozone establish the scatterplot’s x and y variables. Color = Solar.R corresponds to the color of the plot as proportional to the degree of solar radiation.
Line 3: geom_point(na.rm = TRUE) +
Explanation: geom_plot adds points to the “frame” of the scatterplot to represent measured values from the data set, and (na.rm =TRUE) filters out any null values in the dataset before creating a plot.
Line 4: scale_color_gradient(low = “#ADDAFF”, high = “#0064B7”, name = “Solar Radiation”) +
Explanation: scale_color_gradient adds a color gradient to the plot, low = “#ADDAFF” and high = “#0064B7” correspond measurements with solar radiation, with lower values being lighter and higher values being darker, and name = “Solar Radiation” creates a label for the color scale.
Line 5: labs( x = “Solar Radiation”, y = “Ozone Concentration”, title = “Scatterplot of Ozone Concentration by Solar Radiation”, caption = “New York State Conservation and the National Weather Service”)
Explanation: labs() adds labels to the chart. x = “Solar Radiation” is the label for the x axis, y = “Ozone Concentration” is the label for the y axis, title = “Scatterplot of Ozone Concentration by Solar Radiation” is the label for the title, and caption = “New York State Conservation and the National Weather Service”) is the label for the caption.
Line 6: p5
Explanation: p5 displays the plot.
Code 2 for Plot 5 - The r-value
Line 1: solar_radiation <- airquality$Solar.R
Explanation: The solar radiation column (Solar.R) of the airquality dataset (airquality) is transferred to a “storage” called solar_radiation (solar_radiation) by the arrow (<-).
Line 2: ozone_concentration <- airquality$Ozone
Explanation: The ozone column (Ozone) of the airquality dataset (airquality) is transferred to a new “box” called solar_radiation (ozone_concentration) by the arrow (<-).
Line 3: correlation <- cor(solar_radiation, ozone_concentration, use = “complete.obs”)
Explanation: The correlation coefficient between solar_radiation (solar_radiation) and ozone concentration (ozone_concentration) is calculated by the function cor(). “Complete.obs” ensures only data points where both solar radiation and ozone concentrations are present are included in the calculation and then put into the “storage” called correlation (correlation) by an arrow (<-).
Line 4: print(correlation)
Explanation: print(correlation) displays the correlation coefficient.
Code 3 for Plot 5 - The p-value
Line 1: correlation_test <- cor.test(airquality\(Solar.R, airquality\)Ozone)
Explanation: The ozone (Ozone) and solar radiation (Solar.R) columns of the dataset (airquality) are extracted through the dollar sign ($) to calculate a correlation through cor.test and are then put into a “storage” called correlation_test (correlation_test) by an arrow (<-).
Line 2: correlation_p_value <- correlation_test$p.value
Explanation: The p-value (p.value) is extracted from the correlation test (correlation_test) and put into the “storage” called correlation_p_value (correlation_p_value) by an arrow (<-).
Line 3: print(paste(“Correlation P-value:”, correlation_p_value))
Explanation: paste() stores the value of the p-value (correlation_p_value) into the text (“Correlation P-Value”), which is then displayed by print().