Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot in years and month on same axis

Tags:

r

ggplot2

I have the data frame and want to plot Year & Month on X-axis and count on Y- axis.

df1<-data.frame(
  Year=sample(2016:2018,100,replace = T),
  Month=sample(month.abb,100,replace = T),
  category1=sample(letters[1:6],100,replace = T),
  catergory2=sample(LETTERS[8:16],100,replace = T),
  lic=sample(c("P","F","T"),100,replace = T),
  count=sample(1:1000,100,replace = T)
)

Plot :

ggplot(df1,aes(Year,count,fill=factor(lic)))+geom_bar(stat = "identity",position = "stack")+facet_grid(~category1)

Output:

output

But i need year along month as a sequence in a single plot.

like image 700
sai saran Avatar asked May 19 '26 21:05

sai saran


1 Answers

Using lubridate library:

library(lubridate)
library(ggplot2)

df1<-data.frame(
  Year=sample(2016:2018,100,replace = T),
  Month=sample(month.abb,100,replace = T),
  category1=sample(letters[1:6],100,replace = T),
  catergory2=sample(LETTERS[8:16],100,replace = T),
  lic=sample(c("P","F","T"),100,replace = T),
  count=sample(1:1000,100,replace = T)
)

After creating the ymd variable:

df1$ymd <- ymd(paste0(df1$Year, df1$Month, 1))

Then:

ggplot(df1, aes(ymd, count, fill = factor(lic)))+
  geom_bar(stat = "identity", position = "stack")+
  facet_grid(~category1) +

Other options that can help:

# maybe flip coordinates
coord_flip() +

# set scale on axis for each months      
scale_x_date(date_breaks = "1 month")

# using "scales" library, format the date: "YYYY-Mmm"
scale_x_date(date_breaks = "1 month",
             labels = scales::date_format("%Y-%b")) 

# rotate the xaxis labels 90 degrees.
theme(axis.text.x = element_text(angle = 90, vjust = 0.4))
like image 164
Michał Ludwicki Avatar answered May 21 '26 14:05

Michał Ludwicki