I have a data frame called 'm' with 4 columns and about 100 rows.
How can I create a bar plot where I get the right chronological order on the x-axis with months 1-12 repeating for every year?
I have a data frame called 'm' with 4 columns and about 100 rows.
How can I create a bar plot where I get the right chronological order on the x-axis with months 1-12 repeating for every year?
Update on OP's request (see comments):
I have used make_date
from lubridate
package to mutate a new column date
. This time date is class date -> day is set to first of month:
With pivot_longer
we bring the data in correct shape to plot our bars.
Then we use scale_x_date
to show every 4 month.
library(lubridate)
library(tidyverse)
library(scales)
m1 <- m %>%
mutate(date = make_date(YEAR, MONTH)) %>%
pivot_longer(
cols = c(AUTO, IMP),
names_to = "names",
values_to = "values"
)
ggplot(m1, aes(x=date, y=values, fill=names)) +
geom_bar(position='dodge', stat='identity') +
scale_x_date(date_breaks = "4 months" , date_labels = "%b-%y")+
theme_bw()
Original answer:
We create a character column Date
. To be a date we would need a day, therefore we leave it as character class.
With sprintf()
we put the two columns YEAR
and MONTH
together:
library(ggplot2)
m$Date <- with(m, sprintf("%d-%02d", YEAR, MONTH))
ggplot(m, aes(fill=AUTO, y=IMP, x=Date)) +
geom_bar(position='dodge', stat='identity')
data:
m <- structure(list(YEAR = c(2009, 2009, 2009, 2009, 2009, 2009, 2009,
2009, 2009, 2009, 2009, 2009, 2010, 2010, 2010, 2010, 2010, 2010,
2010, 2010, 2010, 2010, 2010, 2010, 2011), MONTH = c(1, 2, 3,
4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 1), AUTO = c(0, 0.003130344, 0.01565172, 0.338077161,
0.01565172, 0, 0, 0.003130344, 0, 0, 0, 0, 0.012277821, 0.021486187,
0.009208366, 0.009208366, 0, 0, 0, 0, 0, 0, 0, 0, 0), IMP = c(0,
0, 0.037564129, 0.062606882, 0.006260688, 0, 0, 0, 0, 0, 0, 0,
0, 0.006138911, 0, 0.003069455, 0, 0, 0, 0, 0, 0, 0, 0, 0)), class = c("spec_tbl_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -25L), spec = structure(list(
cols = list(YEAR = structure(list(), class = c("collector_double",
"collector")), MONTH = structure(list(), class = c("collector_double",
"collector")), AUTO = structure(list(), class = c("collector_double",
"collector")), IMP = structure(list(), class = c("collector_double",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector")), skip = 1L), class = "col_spec"))
set.seed(1)
m <- data.frame(year = rep(2019:2021,each=12),
month = rep(1:12,3),
AUTO = rnorm(36,30,1),
IMP = rnorm(36,20,4)
)
library(dplyr)
library(tidyr)
library(ggplot2)
m %>%
mutate(date = as.Date(paste0(year,"-",month,"-01"))) %>%
pivot_longer(IMP:AUTO,"group","value") %>%
ggplot(., aes(fill=group, y=value, x=date)) +
geom_bar(position='dodge', stat='identity')