Reputation: 45
how can I make one graph from different dates? For example I have data from 2019 and 2020 and would like to display the results in one chart only for months. How can I limit data from a given time period? I want to have one line for 2019 year and the second line for 2020 year.
Date | Microsoft Teams |
---|---|
2019-01-06 | 3 |
2019-03-10 | 10 |
2019-06-09 | 15 |
2019-12-29 | 10 |
2020-01-06 | 25 |
2020-03-10 | 35 |
2020-06-09 | 43 |
2020-12-29 | 39 |
On this graph I want to make another line for year 2020. For this I use this command:
ggplot() + geom_line(data=trendy, aes(x=date, y=`Microsoft Teams`), color="blue")
+ labs(title="Popularność wyszukiwania hasła Microsoft Teams", x="Data", y="Popularność", caption = "")
+ scale_x_date(date_labels = "%B", limit=c(as.Date("2019-01-01"),as.Date("2019-12-31")))
Can someone help me if it's possible?
Upvotes: 1
Views: 340
Reputation: 78927
lubridate
package ymd
to extract year and month from date with month
, year
andas.factor
ggplot
library(tidyverse)
library(lubridate)
df1 <- df %>%
mutate(year = as.factor(year(ymd(Date))),
month = as.factor(month(Date))
)
ggplot(df1, aes(x = month, y = Microsoft.Teams, colour = year, group=year)) +
geom_point()+
geom_line()
Upvotes: 0
Reputation: 48
I am not sure which one do you prefer, but here are two options for you.
trendy <- data %>%
mutate(Date = as.Date(Date),
year = year(Date),
date = paste('2000', month(Date), day(Date), sep = '-'),
date = as.Date(date))
ggplot(data=trendy, aes(x=Date, y=`Microsoft Teams`, color = year)) +
geom_line() +
labs(title="Popularność wyszukiwania hasła Microsoft Teams", x="Data", y="Popularność", caption = "") +
scale_x_date(date_labels = "%B") +
theme_bw()
ggplot(data=trendy, aes(x=date, y=`Microsoft Teams`, color = factor(year))) +
geom_line() +
labs(title="Popularność wyszukiwania hasła Microsoft Teams", x="Data", y="Popularność", caption = "") +
scale_x_date(date_labels = "%B") +
theme_bw()
Upvotes: 1
Reputation: 8107
library(tidyverse)
library(lubridate)
Preparing the data:
dat <- tribble(~Date, ~Teams,
"2019-01-06", 3,
"2019-03-10", 10,
"2019-06-09", 15,
"2019-12-29", 10,
"2020-01-06", 25,
"2020-03-10", 35,
"2020-06-09", 43,
"2020-12-29", 39)
dat <- mutate(dat, Date = parse_date(Date))
The trick is to separate the dates into years and months, and then map years as the colour dimension in the chart:
dat %>%
mutate(years = as.character(year(Date)), months = month(Date, label = TRUE)) %>%
ggplot(aes(x = months, y = Teams, colour = years, group = years)) +
geom_line()
Upvotes: 1