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:

But i need year along month as a sequence in a single plot.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With