Home > Software engineering >  ggplot: defining sexond axis changes format of first axis
ggplot: defining sexond axis changes format of first axis

Time:03-16

I make a plot using ggplot2 with dates like this:

df <- data.frame(date= sample(seq(from=as.Date("2015-01-01"),length.out=100,by="day")))
my_plot <- ggplot(df, aes(date))  
  geom_density()
my_plot

ok

This looks as expected. But as soon as I define a sexond axis the format of the first changes:

my_plot  
  scale_x_continuous(sec.axis = sec_axis(~ . , name = "test", breaks = NULL, labels = NULL))

wrong

In this example the second axis could be replaced with labs(title= "test"). It is just a minimal reproducible example. No matter how we define the second axis the first x axis does not show month anymore but numbers instead. How can I define a second axis without changing the format of the first?

CodePudding user response:

It's not the second axis that causes the problem, it's that you are specifying scale_x_continuous instead of scale_x_date:

my_plot  
  scale_x_date(sec.axis = sec_axis(~ . , name = "test", breaks = NULL, labels = NULL))

enter image description here

  • Related