Matplotlib绘图配置:让两幅图贴合窗口并正常显示日期轴
解决Matplotlib多独立Figure的布局调整问题
我懂你现在的困扰——两个独立的Matplotlib绘图窗口,想让图形紧贴窗口边缘,同时让日期X轴的标签完整显示,但用plt.subplots_adjust()只对其中一个图生效,tight_layout()也没起作用对吧?
问题根源
你创建了两个完全独立的figure对象(fig1和fig2),而plt.subplots_adjust()默认只会作用于当前活跃的那个Figure(也就是你最后创建的fig2),所以之前的设置只修改了第二个图的布局;而你没有针对每个Figure单独调用tight_layout(),自然也不会对两个图都生效。
解决方案:针对每个Figure单独调整布局
我们只需要对每个创建好的Figure对象,单独调用布局调整方法即可,两种方式都可行:
方式1:使用tight_layout()(推荐,自动适配边距)
tight_layout()会自动计算图形、标签、刻度之间的间距,帮你把所有元素都完整显示出来,不用手动调参数。
方式2:使用figure.subplots_adjust()
如果你需要精确控制边距数值,可以针对每个Figure对象调用subplots_adjust(),而不是用全局的plt.subplots_adjust()。
修改后的完整代码
import numpy as np import matplotlib.pyplot as plt import time from datetime import datetime, timedelta import matplotlib.dates as mdates EQ = { '2017-08-23 02:04:00':(18,1), '2017-08-23 02:05:00':(20,2), '2017-08-23 02:06:00':(12,3), '2017-08-23 02:07:00':(22,4) } LIST_P1 = [] LIST_P2 = [] Time_P = [] for j_p in EQ.keys(): LIST_P1.append(EQ[j_p][1]) LIST_P2.append(EQ[j_p][0]) Time_P.append(time.mktime(time.strptime(j_p, "%Y-%m-%d %H:%M:%S"))) dateconv = np.vectorize(datetime.fromtimestamp) Date_F1 = dateconv(Time_P) # 处理第一个绘图窗口 fig1 = plt.figure(1) ax1 = plt.gca() ax1.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d %H:%M:%S")) ax1.plot_date(Date_F1, LIST_P1, 'g-') ax1.set_ylabel('Y-axis', fontsize=14) ax1.set_xlabel('X-axis', fontsize=14) ax1.grid(True) for label in ax1.xaxis.get_ticklabels(): label.set_rotation(45) # 针对fig1自动调整布局 fig1.tight_layout() # 处理第二个绘图窗口 fig2 = plt.figure(2) ax2 = plt.gca() ax2.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d %H:%M:%S")) ax2.plot_date(Date_F1, LIST_P2, 'g-') ax2.set_ylabel('Y-axis', fontsize=14) ax2.set_xlabel('X-axis', fontsize=14) ax2.grid(True) for label in ax2.xaxis.get_ticklabels(): label.set_rotation(45) # 针对fig2自动调整布局 fig2.tight_layout() plt.show()
效果说明
修改后,两个绘图窗口都会自动调整边距,让X轴的日期标签完整显示,同时图形会紧密贴合窗口边缘,达到你想要的效果。如果需要更精细的布局控制,把fig1.tight_layout()换成fig1.subplots_adjust(left=0.07, right=0.985, bottom=0.16, top=0.955)即可,第二个图同理。
内容的提问来源于stack exchange,提问作者Ahmet
相关产品推荐
相关产品推荐

