Verdoux
Verdoux

Reputation: 45

Making one plot with two years

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

enter image description here

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

Answers (3)

TarJae
TarJae

Reputation: 78927

  1. Use lubridate package ymd to extract year and month from date with month, year and
  2. Make both factor with as.factor
  3. Then plot with 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() 

enter image description here

Upvotes: 0

Yingjie
Yingjie

Reputation: 48

I am not sure which one do you prefer, but here are two options for you.

manipulate data

trendy <- data %>%
  mutate(Date = as.Date(Date),
         year = year(Date),
         date = paste('2000', month(Date), day(Date), sep = '-'),
         date = as.Date(date))

plot 1

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()

plot 2

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

Phil
Phil

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()

enter image description here

Upvotes: 1

Related Questions