[英]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.我想创建两个具有相同 x 轴标签的图形,然后使用
plot_grid()
对齐它们。
Here is what the result currently looks like:以下是当前的结果:
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.如您所见,上图的 x 轴从 3 月开始(这是我想要的),但下图的 x 轴从 1 月开始。 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))
.我使用了完全相同的代码行,为两个图表指定 x 轴,即:
scale_x_date(date_breaks = "3 month", date_labels = "%m-%Y", expand = c(0, 0))
。
Here is the ggplot code for the two graphs:这是两个图表的 ggplot 代码:
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!
我真的很感激一些帮助!
Just like Roman mentioned in the comments, specifying the breaks
worked.就像评论中提到的 Roman 一样,指定
breaks
是有效的。 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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.