PeCaDe
PeCaDe

Reputation: 374

wrong dates at x axis when plotting POSIXct with scale_x_datetime

From the following dataframe df:

df <- data.frame(Date=as.POSIXct(c("2002-07-01","2002-06-01","2002-05-01","2002-04-01","2002-03-01")),
                 Cat1=c(1,0,1,0,0),
                 Cat2=c(1,1,1,0,0),
                 Cat3=c(0,1,1,0,1),
                 Cat4=c(0,0,1,1,0))

df <- tidyr::pivot_longer(df, -1)

When using scale_x_datetime this require POSIXct class object, otherwise this complaints with error.

Error: Invalid input: time_trans works with objects of class POSIXct only

ggplot(df,
       aes(x = Date, y = factor(name, levels = rev(unique(name))), 
           fill = as.factor(value))) +
  geom_tile(color = "black") +
  scale_fill_manual(values = c("white", "grey50")) +
  theme_void() +
  theme(legend.position = "none",
        axis.text = element_text(size = 8),
        plot.margin = margin(20, 20, 20, 20),
        axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1, size =5))+
  scale_x_datetime(date_breaks = "1 month",
                   labels = scales::date_format("%m-%Y"))

With the following input: enter image description here

By inspecting the range of Date column, this does not match with plot labels from x-axis.

range(df$Date)

Does anyone how to solve this?

Upvotes: 1

Views: 539

Answers (1)

tjebo
tjebo

Reputation: 23737

Use date class, and scale_x_date

library(ggplot2)

# changing the class by constructing your data differently
df <- data.frame(Date=as.Date(c("2002-07-01","2002-06-01","2002-05-01","2002-04-01","2002-03-01")),
                 Cat1=c(1,0,1,0,0),
                 Cat2=c(1,1,1,0,0),
                 Cat3=c(0,1,1,0,1),
                 Cat4=c(0,0,1,1,0))

df <- tidyr::pivot_longer(df, -1)

ggplot(df,
       aes(x = Date, y = factor(name, levels = rev(unique(name))), 
           fill = as.factor(value))) +
  geom_tile(color = "black") +
  scale_fill_manual(values = c("white", "grey50")) +
  theme_void() +
  theme(legend.position = "none",
        axis.text = element_text(size = 8),
        plot.margin = margin(20, 20, 20, 20),
        axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1, size =5))+
  scale_x_date(labels = scales::date_format("%m-%Y"))

Created on 2021-11-02 by the reprex package (v2.0.1)

Upvotes: 1

Related Questions