The dataset I chose is the carbon emmissions dataset to creat a scatter plot that shows land, air, and sea anomalies. Also, an average line was created to show the averages of each variable over the time period.
#Loading Packages from library
library(dslabs)
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.3 ✔ 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
library(ggplot2)
library(dplyr)
library(RColorBrewer)
#Shows First Six Rows of Dataset
head(temp_carbon)
## year temp_anomaly land_anomaly ocean_anomaly carbon_emissions
## 1 1880 -0.11 -0.48 -0.01 236
## 2 1881 -0.08 -0.40 0.01 243
## 3 1882 -0.10 -0.48 0.00 256
## 4 1883 -0.18 -0.66 -0.04 272
## 5 1884 -0.26 -0.69 -0.14 275
## 6 1885 -0.25 -0.56 -0.17 277
#Loading the Data Set in the Environment
data("temp_carbon")
#Filter the years from 1880 to 2018
temp_carbon <- temp_carbon %>%
filter(year >= 1880 & year <= 2018)
# Transform the data to long format for easier plotting
temp_long <- temp_carbon %>%
select(year, temp_anomaly, land_anomaly, ocean_anomaly) %>%
gather(key = "category", value = "value", -year)
# Define colors for points and lines
category_colors <- c("temp_anomaly" = "blue", "land_anomaly" = "red", "ocean_anomaly" = "green")
# Create the scatter plot
ggplot(temp_long, aes(x = year, y = value, color = category)) +
# Add scatter plot points
geom_point(size = 2, alpha = 0.5) +
# Add a smooth line (optional, remove if not needed)
geom_smooth(method = "lm", se = FALSE, aes(color = category), size = 1) +
# Use the defined colors for each category
scale_color_manual(values = category_colors) +
# Add meaningful labels
labs(title = "Temperature Anomalies on Air, Land, and Sea(1880-2018)",
x = "Year",
y = "Temperature Anomaly (C)",
color = "Category") +
# Customize the theme
theme_minimal(base_size = 15) +
theme(legend.position = "right",
plot.title = element_text(hjust = 0.5, size = 10)) # Center the plot title and decrease size
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## `geom_smooth()` using formula = 'y ~ x'