Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show date x-axis labels every 3 or 6 months in ggplot2

Tags:

r

ggplot2

I generate a plot with code below:

ggplot(reshaped_median, aes(x= Month_Yr, y = value))+ 
geom_line(aes(color = Sentiments)) + 
geom_point(aes(color = Sentiments)) + 
labs(title = 'Change in Sentiments (in median)', x = 'Month_Yr', y = 'Proportion of Sentiments %') + 
theme(axis.text.x = element_text(angle = 60, hjust = 1))

enter image description here

But as you can notice the dates labels in x-axis are too dense, so if I want to it displays date quarterly or on the half year (every 3 or 6 months).

The values from Month_Yr are with format %Y-%m.

How could I do that? Thanks.

like image 409
ah bon Avatar asked Dec 31 '22 02:12

ah bon


2 Answers

First convert date by: df$Month_Yr <- as.Date(as.yearmon(df$Month_Yr))

Then use this can solve the issue:

ggplot(reshaped_median, aes(x= Month_Yr, y = value))+ 
  geom_line(aes(color = Sentiments)) + 
  geom_point(aes(color = Sentiments)) + 
  #Here you set date_breaks  ="6 month" or what you wish
  scale_x_date(date_labels="%b-%d",date_breaks  ="3 month")+
  labs(title = 'Change in Sentiments (in median)', x = 'Month_Yr', y = 'Proportion of Sentiments %') + 
  theme(axis.text.x = element_text(angle = 60, hjust = 1))
like image 119
Duck Avatar answered Jan 13 '23 16:01

Duck


Here's another way. With scale_x_date you can manipulate the breaks on your x-axis easily.

library(ggplot2)
library(tibble)

data <- tibble(
  Month_Yr = seq.Date(from = as.Date("2010/01/01"), to =  as.Date("2020/01/31"), by = "month"),
  Value = runif(121, min = 0, max = 150)
)


p <- ggplot(data = data, aes(x = Month_Yr, y = Value)) + 
  geom_point() +
  theme(axis.text.x = element_text(angle = 60, hjust = 1)) +
  scale_x_date(date_breaks = "6 months")
p
like image 23
Paul van Oppen Avatar answered Jan 13 '23 15:01

Paul van Oppen