'Problem while plotting in grouped date values in R
I was trying to plot the max values from a dataset with x-axis = Date and the y-axis = max_value grouped by Stations, like the picture I found on this link, but I would like to make 5 plots (from different Stations).
This is a sample of my df:
df2 <- data.frame (Station = c(1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 10, 10, 10),
Date = c("1/1/2018", "2/1/2018", "3/1/2018","1/1/2018", "2/1/2018", "3/1/2018","1/1/2018", "2/1/2018", "3/1/2018","1/1/2018", "2/1/2018", "3/1/2018","1/1/2018", "2/1/2018", "3/1/2018"),
MAX_NO2 = c(55,52,58,76,98,12,14,23,54,76,90,99,43,32,76),
MAX_O3 = c(13,45,87,72,54,88,102,63,64,53,87,123,15,76,34))
This is the code I have:
library(tidyverse)
library(lubridate)
# your data
df2 %>%
# add date as date
mutate(date = ymd(Date)) %>%
# plot them
ggplot( aes(x = date, y = MAX_NO2 , color = Station==1, group = Station==1)) +
geom_line() + geom_point() + theme_test()
But this is what I am plotting (this is from all the dataframe, not the sample):
Where the blue dots are the max values from the Station Nº1.That's the only thing I want to plot, not the other ones in the same plot. In plot 1 Station 1, in plot 2 Station 2, etc.
Solution 1:[1]
The data.frame you provided is different from the plot. But if you want to get different plots for every station at once.Not calling a different ggplot for every station, maybe the facet_wrap() function (or facet_grid()) is helpful:
library(tidyverse)
library(lubridate)
df2 <- data.frame (Station = c(1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 10, 10, 10),
Date = c("1/1/2018", "2/1/2018", "3/1/2018","1/1/2018", "2/1/2018", "3/1/2018","1/1/2018", "2/1/2018", "3/1/2018","1/1/2018", "2/1/2018", "3/1/2018","1/1/2018", "2/1/2018", "3/1/2018"),
MAX_NO2 = c(55,52,58,76,98,12,14,23,54,76,90,99,43,32,76),
MAX_O3 = c(13,45,87,72,54,88,102,63,64,53,87,123,15,76,34))
df2 %>%
mutate(Station = as.character(Station)) %>%
ggplot(aes(x = Date, y = MAX_NO2, colour=Station, group=Station)) +
geom_line() + geom_point() + theme_test() +
facet_wrap(~Station)
I can't show a plot with SO2 because the data is different. Also, note that ymd(date)is wrong, should be dmy(Date).
Solution 2:[2]
As mentioned in the comments, it is easiest to remove the other stations before plotting with ggplot2, so that you only keep the data that you need to plot. Also, for converting the date, I think you may want dmy or mdy instead of ymd (at least from your sample data).
library(tidyverse)
library(lubridate)
df2 %>%
# add date as date
mutate(date = mdy(Date)) %>%
filter(Station == 1) %>%
# plot them
ggplot( aes(x = date, y = MAX_NO2 , color = Station, group = Station)) +
geom_line() +
geom_point() +
theme_test()
Output
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RobertoT |
| Solution 2 | AndrewGB |



