I would like to create a line graph that shows how the trend of five air pollutants were during the years 2009 to 2019.
| Year | CO2 | NO2 | O3 | PM2.5 |
|---|---|---|---|---|
| 2009 | 30 | 18 | 20 | 30 |
| 2010 | 32 | 16 | 22 | 20 |
| 2011 | 33 | 16 | 24 | 20 |
| 2012 | 32 | 15 | 25 | 22 |
| 2013 | 34 | 14 | 27 | 24 |
| 2014 | 36 | 14 | 28 | 22 |
| 2015 | 38 | 13 | 29 | 20 |
| 2016 | 39 | 13 | 30 | 18 |
| 2017 | 40 | 12 | 32 | 16 |
| 2018 | 44 | 13 | 34 | 15 |
| 2019 | 45 | 11 | 38 | 14 |
I gave that code but it is a histogram, i would like to have a line graph were all four are in the same plot.
df %>%
ggplot(aes(x = Year, y = n, fill = airpollutants)) +
geom_col() +
facet_wrap(~Year) + ggtitle("trend of airpollutants")
I want this output:
https://cdn.ablebits.com/_img-blog/line-graph/line-graph-excel.png
>Solution :
set.seed(123)
library(ggplot2)
library(tidyr)
# Example data
df <- data.frame(year = 2009:2019,
CO2 = sample(30:40, 11),
NO2 = sample(10:20, 11),
O3 = sample(20:30, 11),
PM2.5 = sample(15:25, 11))
# Convert to long format
df_long <- pivot_longer(df,
cols = c(CO2, NO2, O3, PM2.5),
values_to = "Concentration",
names_to = "Pollutant")
# Plot
ggplot(df_long,
aes(
x = year,
y = Concentration,
color = Pollutant,
linetype = Pollutant
)) +
geom_line(size = 0.7) +
ggtitle("Trend of Airpollutants") +
xlab("Year") +
ylab("Concentration") +
scale_x_continuous(breaks = seq(2009, 2019, by = 1), limits = c(2009,2019)) +
theme_minimal()
