R 具有相同参数的两个图形在ggplot中具有不同的x轴

R 具有相同参数的两个图形在ggplot中具有不同的x轴,r,ggplot2,R,Ggplot2,我想创建两个具有相同x轴标签的图形,然后使用plot\u grid()将它们对齐 以下是当前的结果: 如您所见,上部图形的x轴从3月份开始(这是我想要的),但下部图形的x轴从1月份开始。我使用了完全相同的代码行来指定这两个图形的x轴,即:缩放x_日期(date_breaks=“3个月”,date_标签=“%m-%Y”,expand=c(0,0)) 以下是两个图形的ggplot代码: 上部图形代码: PS_color <- c("Precipitation" = &qu

我想创建两个具有相同x轴标签的图形,然后使用
plot\u grid()
将它们对齐

以下是当前的结果:

如您所见,上部图形的x轴从3月份开始(这是我想要的),但下部图形的x轴从1月份开始。我使用了完全相同的代码行来指定这两个图形的x轴,即:
缩放x_日期(date_breaks=“3个月”,date_标签=“%m-%Y”,expand=c(0,0))

以下是两个图形的ggplot代码:

上部图形代码:

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")
   ) 
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")
  )

PS\u color就像评论中提到的Roman一样,指定
中断
有效。因此,我创建了一个包含以下日期的向量:

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) 

手动指定x轴断开,您应该可以继续。此外,尝试设置两个图形的限制。从
ggplot
文档中,您作为
scale\u xxx\u yyy
参数提供的
break
s等不保证准确执行。(例如,请参见
n.breaks
)当我需要精确控制刻度的范围时,调用
coord_cartesian()
通常就可以了。详细信息请参阅。@RomanLuštrik谢谢,成功了!
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) 
scale_x_date(breaks = Date1, date_labels = "%m-%Y", expand = c(0, 0))