Phil
Phil

Reputation: 85

Two graphs with the same arguments have different x-axes in ggplot

I want to create two graphs that have the same x-axis labels and then use plot_grid() to align them.

Here is what the result currently looks like:

enter image description here

As you can see, the x-axis of the upper graph begins in March (which is I what I want) but the x-axis of the lower graph begins in January. I used the exact same line of code specifiying the x-axis for both graphs which is: scale_x_date(date_breaks = "3 month", date_labels = "%m-%Y", expand = c(0, 0)).

Here is the ggplot code for the two graphs:

Upper graph code:

PS_color <- c("Precipitation" = "blue", "Snowdepth" = "red")
 tmp <- ggplot(dfQ1, aes(x = Date)) + 
  geom_col(aes(y = Precipitation, color = "Precipitation")) + 
  geom_col(aes(y = Snowdepth, color = "Snowdepth")) + 
  labs(x = "Month-Year", 
       y = "Precipitation [mm] and snowdepth [cm]", 
       color = "Legend") + 
  scale_color_manual(values = PS_color, labels = c("Precipitation", "Snow depth")) + 
  scale_x_date(date_breaks = "3 month", date_labels = "%m-%Y", expand = c(0, 0)) + 
  theme_bw() + 
   theme(panel.grid.minor = element_blank(), 
         axis.line = element_line(), 
         legend.title.align = 0.5
         #legend.title = element_text(face = "bold")
   ) 

Lower graph code:

Q_color <- c("Discharge" = "black")
plot_Q_2012_2013 <- ggplot(dfQ1, aes(x = Date)) +  
  geom_line(aes(y = Discharge, color = "Discharge")) + 
  labs(x = "Month-Year", 
       y = "Discharge [mm]",
       color = "Legend") +  
   scale_color_manual(values = Q_color) +
   scale_x_date(date_breaks = "3 month", date_labels = "%m-%Y", expand = c(0, 0)) + 
   scale_y_continuous(limits = c(0,17), expand = c(0,0)) + 
  theme_bw() + 
  deforestation_period + 
  theme(panel.grid.minor = element_blank(), 
        axis.line = element_line(), 
        legend.title.align = 0.5
        #legend.title = element_text(face = "bold")
  )

Code to align both graphs:

rev_plot <- tmp + scale_y_reverse(limits = c(83,0), expand = c(0,0))
plot_grid(rev_plot, plot_Q_2012_2013, nrow = 2) 

Unfortunately I can not post the two dataframes completely because there would be too many characters for a post here.

Do you know how I can fix this? I'd really appreciate some help!

Upvotes: 0

Views: 340

Answers (1)

Phil
Phil

Reputation: 85

Just like Roman mentioned in the comments, specifying the breaks worked. Thus I created a vector containing dates with:

Dates <- c("2012-03-01", "2012-06-01", "2012-09-01", "2012-12-01", 
           "2013-03-01", "2013-06-01", "2013-09-01", "2013-12-01")
Date1 <- as.Date(Dates) 

Afterwards I wrote:

scale_x_date(breaks = Date1, date_labels = "%m-%Y", expand = c(0, 0))

Upvotes: 1

Related Questions