Eisen
Eisen

Reputation: 1897

Plotting a bar graph in R with two character date columns

I have a dataframe like so:

month year count
1    2020  2301
2    2020  2311
3    2020  2417
4    2020  2205
5    2020  2399
6    2020  2367

I want to convert the dataset to something like this where the date column is actually of date type:

date    count
1/2020  2301
2/2020  2311
3/2020  2417
4/2020  2205
5/2020  2399
6/2020  2367

and then plot in gggplot using date as x axis and count as y axis.. How can i do this in R?

Upvotes: 0

Views: 85

Answers (1)

akrun
akrun

Reputation: 887881

With lubridate, we can convert to Date class with ymd after pasteing the 'year', 'month' and using truncated. Then, change the format in x axis

library(lubridate)
library(dplyr)
library(scales)
library(ggplot2)
library(stringr)
df1 %>%
   mutate(date = ymd(str_c(year, "/", month), truncated = 1)) %>% 
   ggplot(aes(x = date, y = count)) +
    geom_col()+
    scale_x_date(labels = date_format('%m/%Y'))

Upvotes: 1

Related Questions