Skip to main content
 首页 » 编程设计

python之Matplotlib 在图中填充空白

2025年04月02日15sharpest

我在 matplotlib 中绘制了一个共享轴图,如下所示:

我尝试了很多方法来在 X 轴的 Jan 和 Dec 附近填充一点空白,以使其看起来更美观,但找不到任何方法来做到这一点。有人可以对此提出建议吗?

我的代码:

fig, axes1 = plt.subplots(figsize=(12,8)) 
 
axes1.plot(misr_aod, label='MISR', color='blue', linestyle=':', linewidth=2, marker='+') 
axes1.plot(modis_aod, label='MODIS', color='green', linestyle='-.', linewidth=2, marker='o') 
axes1.plot(CESM_aod, label='CESM_AOD', color='red', linestyle='--', linewidth=2, marker='s') 
axes1.set_ylim([0,0.8]) 
axes1.legend(loc=2) 
axes1.set_xticks([-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) 
axes1.set_xticklabels(['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', '']) 
axes1.grid(True) 
axes1.set_xlabel('Months') 
axes1.set_ylabel('AOD at 500 nm') 
 
 
axes2 = axes1.twinx() 
 
axes2.plot(APHRO_pcp, label='APHRO', color="magenta", linewidth=2, markerfacecolor="yellow", markeredgewidth=2, markeredgecolor="blue") 
axes2.plot(IMD_pcp, label='IMD', color="purple", linewidth=2) 
axes2.plot(TRMM_pcp, label='TRMM', color="green", linewidth=2) 
axes2.plot(CESM_pcp, label='CESM_PRECT', color="red", linewidth=2) 
axes2.set_ylim([0,10]) 
yticks = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
axes2.set_yticks(yticks) 
axes2.set_ylabel('PRECIPITATION (mm/day)') 
axes2.legend() 
plt.show() 

请您参考如下方法:

您可以使用 ax.margins()在 x 轴上的数据前后自动填充一些空间。

对于你的脚本,你只需要像这样的东西:

axes1.margins(x=0.05) 

在两端添加 5% 的 x 范围。显然,您只需要调整 x 以满足您的需要。