ggplot中scale_y_break轴断面板比例不符,如何调整?
解决ggplot轴断点上面板过大的问题
问题说明
需要在ggplot的Y轴1.0至2.5位置添加轴断点,使断点上方的面板尺寸小于下方,但使用scale_y_break(c(1.0, 2.5))时,断点前后的两个面板采用相同比例,导致上方面板过大,无法达到期望效果。
期望效果

当前效果

解决方案
使用ggbreak包的scale_y_break()函数时,可通过space参数自定义断点上下两个面板的相对高度比例。参数值为一个长度为2的向量,分别对应下方和上方面板的高度权重,权重越小面板越窄。例如设置space = c(5, 1),表示下方面板高度是上方的5倍,即可让上方面板尺寸缩小。
同时需要修正原代码中的列名不一致问题(数据框中是Amonia Load,ggplot映射时误用了Amonia.Load)。
修改后的测试代码
# 加载所需包 library(ggplot2) library(ggbreak) # Generate fake ammonia load data set.seed(123) # For reproducibility dates <- seq(as.Date("2024-01-01"), as.Date("2024-12-31"), by="week") ammonia_load <- runif(length(dates), min=0, max=0.35) # Random data between 0 and 0.35 # Create a data frame df <- data.frame(Date = dates, `Amonia Load` = ammonia_load) # Create plot with adjusted panel space Figure <- ggplot(df, aes(x=Date, y=`Amonia Load`)) + geom_point(color="black", fill="blue", shape=21, size=2) + labs(x="", y="Load (kg/day)") + theme_classic() + scale_x_date(date_breaks="1 month", date_labels="%b") + scale_y_continuous(limits=c(0.0, 3.0), breaks = c(0.0,0.2,0.4,0.6,0.8,1.0,2.5,3.0)) + theme(panel.border = element_rect(color="black", fill=NA, size=0.5), text = element_text(size=12), axis.text = element_text(size=12), axis.title = element_text(size=12)) + geom_hline(yintercept=2.8, linetype="dashed", color="black") + # 设置space参数调整面板比例 scale_y_break(c(1.0, 2.5), space = c(5, 1)) Figure
内容的提问来源于stack exchange,提问作者confusedindividual
相关产品推荐
相关产品推荐

