Mojtaba
Mojtaba

Reputation: 316

Strange behaviour of Subplot in Matplotlib when used by plotfile

I have a script for drawing subplots which works perfectly for ploting bars. When I use this script with plotfile function, the outcome is just one plot on top of another. Basically it just shows the second plot. What is the reason for that?

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)

Upvotes: 2

Views: 191

Answers (2)

Bertrand Caron
Bertrand Caron

Reputation: 2657

After looking at the content of the pyplot.py package, I realised that the plotfile function did not interface well with subplots: if you want to plot multiple columns of a file to subplots, it can easily do that.

If you want to arbitrarily plot multiple (potentially different) files to different subplots, then it can't.

The solution I found was to use numpy genfromtxt to read the data myself by writing our own plot_file function:

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()

Upvotes: 1

xnx
xnx

Reputation: 25478

Could be because of this from the docs about the newfig 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 defaults to True. Try passing newfig=False to pylab.plotfile.

Upvotes: 0

Related Questions