'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?



Solution 1:[1]

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

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 akrun