Skip to main content
 首页 » 编程设计

python之当 plotfile 使用时,Matplotlib 中 Subplot 的奇怪行为

2025年05月04日16lyj

我有一个用于绘制子图的脚本,它非常适合绘制条形图。当我将此脚本与 plotfile 函数一起使用时,结果只是一个图叠加在另一个图上。基本上它只显示第二个情节。这是什么原因?

import matplotlib 
matplotlib.use('Agg') 
 
import matplotlib.pylab as plt 
import numpy as np 
import matplotlib.ticker as mtick 
from operator import add 
 
matplotlib.rcParams.update({'font.size': 16}) 
 
fig = plt.figure(figsize=(11,10)) 
plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.13, hspace=0.15) 
 
ax1=fig.add_subplot(211) 
plt.plotfile('2m_5m_stringsearch', delimiter=' ', cols=(0, 1), color='green', linewidth= 1.5, linestyle='-.',dashes=(5,8), marker='', label='stringsearch') 
plt.ylim(0,1) 
ax1.set_xticklabels([]) 
plt.ylabel('SER of Leon3-C1') 
 
ax2=fig.add_subplot(212) 
plt.plotfile('2m_5m_stringsearch', delimiter=' ', cols=(0, 1), color='green', linewidth= 1.5, linestyle='-.',dashes=(5,8), marker='', label='stringsearch') 
plt.ylim(0,1) 
ax2.set_xticklabels([]) 
plt.ylabel('SER of Leon3-C2') 
 
plt.savefig("Output.pdf", dpi=400, bbox_inches='tight', pad_inches=0.05) 

请您参考如下方法:

在查看了pyplot.py 包的内容后,我意识到plotfile 函数没有很好地与子图接口(interface):如果你想绘制多列一个文件到子图,它可以很容易地做到这一点。

如果您想将多个(可能不同的)文件任意绘制到不同的子图中,则不能。

我找到的解决方案是使用 numpy genfromtxt 通过编写我们自己的 plot_file 函数自己读取数据:

import numpy as np 
def plot_file(ax, fnme, cols=[], label=None): 
    data = np.genfromtxt( 
      fnme, 
      skip_header=0, 
      skip_footer=0, 
      names=[str(col) for col in cols], 
    ) 
    ax.plot(*[data[str(col)] for col in cols], label=label) 
 
import matplotlib.pyplot as plt    
fig = plt.figure(figsize=(10, 3)) 
PLOT_INDEXES = range(0,2) 
for i in PLOT_INDEXES: 
    ax = plt.subplot(1, len(PLOT_INDEXES), i+1) 
    plot_file(ax, 'test_{0}.txt'.format(i), cols=[0, 1], label=str(i)) 
plt.show()