MatPlotLib is very slow in python
<pre><code>import matplotlib
matplotlib.use('TkAgg')
def generate_graph(self,subject,target,filename):
    x_data = range(0, len(self.smooth_hydro))
    mslen = len([i[1] for i in self.master_seq.items()][0])
    diff=(mslen-len(self.smooth_hydro))/2
    x1_data = range(0,len(self.smooth_groups.items()[0][-1]))
    x2_data = range(0,mslen)
    plt.figure()
    plt.axhline(y=0, color='black')
    plt.ylim(-3, 3)
    plt.xlim(right=mslen)
    plt.plot(x_data, self.smooth_hydro, linewidth=1.0, label="hydrophobicity", color='r')
    plt.plot(x_data, self.smooth_amphi, linewidth=1.0, label="amphipathicity", color='g')
    for pos in self.hmmtop:
        plt.axvline(x=pos-1-diff, ymin=-2, ymax = 0.1, linewidth=1, color='black',alpha=0.2)

    plt.axvspan(subject[0]-diff,subject[1]-diff, facecolor="orange", alpha=0.2)
    plt.axvspan(target[0]-diff,target[1]-diff, facecolor="orange", alpha=0.2)

    plt.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05),
              ncol=3, fancybox=True, shadow=True)
    plt.xlabel("Residue Number")
    plt.ylabel("Value")
    width = (0.0265)*len(self.master_seq[0]) if mslen &gt; 600 else 15
    plt.grid('on')
    plt.savefig(self.out+'/graphs/'+filename+'.png')
    plt.clf()
    plt.cla()
    plt.close()
</code></pre>

<p>I am calling this function repeatedly, but the images generated are extremely slow. Can someone please help me optimize this code so that it can run faster?</p>

<p>Thank you!</p>

<p>I found this answer in another <a href="http://stackoverflow.com/a/11093027/5104387">post</a>. All credit to <a href="http://stackoverflow.com/users/643629/luke">Luke</a>.</p>

<blockquote>
  <p>Matplotlib makes great publication-quality graphics, but is not very
  well optimized for speed. There are a variety of python plotting
  packages that are designed with speed in mind:</p>
  
  <ul>
  <li><p><a href="http://pyqwt.sourceforge.net/" rel="nofollow">http://pyqwt.sourceforge.net/</a> [ edit: pyqwt is no longer
  maintained;the previous maintainer is recommending pyqtgraph ]</p></li>
  <li><p><a href="http://code.google.com/p/guiqwt/" rel="nofollow">http://code.google.com/p/guiqwt/</a></p></li>
  <li><p><a href="http://code.enthought.com/projects/chaco/" rel="nofollow">http://code.enthought.com/projects/chaco/</a> </p></li>
  <li><p><a href="http://www.pyqtgraph.org/" rel="nofollow">http://www.pyqtgraph.org/</a></p></li>
  </ul>
</blockquote>

python matplotlib