当被plotfi使用时Matplotlib中子批的奇怪行为

2024-05-20 22:59:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用于绘制子图的脚本,非常适合绘制条形图。当我将这个脚本与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)

Tags: import脚本noneadd绘图matplotlibasfig
2条回答

在查看了pyplot.py包的内容之后,我意识到plotfile函数与子批的接口不好:如果您想将文件的多个列打印到子批,它可以很容易地做到这一点。你知道吗

如果您想任意地将多个(可能不同的)文件打印到不同的子图,那么它就不能

我找到的解决方案是使用numpygenfromtxt通过编写我们自己的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()

可能是因为this from the docs about the ^{} argument

If newfig is True, the plot always will be made in a new figure; if False, it will be made in the current figure if one exists, else in a new figure.

newfig默认为True。尝试将newfig=False传递给pylab.plotfile。你知道吗

相关问题 更多 >