Re: [Matplotlib-users] Would like to update visible plot using pyside and matplotlib

2012-10-22 Thread troyrock
I figured out the problem.  I need to call self.canvas.draw() in order to
update the image.  Sorry for the email.



--
View this message in context: 
http://matplotlib.1069221.n5.nabble.com/Would-like-to-update-visible-plot-using-pyside-and-matplotlib-tp39576p39577.html
Sent from the matplotlib - users mailing list archive at Nabble.com.

--
Everyone hates slow websites. So do we.
Make your web apps faster with AppDynamics
Download AppDynamics Lite for free today:
http://p.sf.net/sfu/appdyn_sfd2d_oct
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


[Matplotlib-users] Would like to update visible plot using pyside and matplotlib

2012-10-22 Thread troyrock
I have a tool to show information extracted from various experiments and then
stored in a database.  I would like to update a plot shown in the lower half
of the window when information such as the ranges of variables are modified
in the upper half.  I can initially put data into the plot, however when I
want to change the contents (such as add another line to the plot), the 
changes don't get displayed.  Here is some code to illustrate the problem:

import matplotlib
matplotlib.rcParams['backend.qt4'] = 'PySide'
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
matplotlib.use('Qt4Agg')
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as
FigureCanvas
from PySide import QtCore, QtGui
import sys


class TabDialog(QtGui.QDialog):
   def __init__(self):
  super(TabDialog, self).__init__()

  tabWidget = QtGui.QTabWidget()
  tabWidget.addTab(AnalyzeTab(), self.tr("Analyze"))

  buttonLayout = QtGui.QHBoxLayout()
  saveButton = QtGui.QPushButton(self.tr("Update"))
  saveButton.clicked[bool].connect(self.update)
  buttonLayout.addWidget(saveButton)

  mainLayout = QtGui.QVBoxLayout()
  mainLayout.addWidget(tabWidget)
  mainLayout.addLayout(buttonLayout)
  self.setLayout(mainLayout)

   def update(self):
  data.update()

class DataHolder():
   def __init__(self):
  self.gFig = Figure()
  self.ax = self.gFig.add_subplot(111)
  self.ax.plot([1,2,4,0.1])
  self.canvas = FigureCanvas(self.gFig)

   def update(self):
  self.ax.plot([8,6,4,2])

class AnalyzeTab(QtGui.QWidget):
   def __init__(self, parent=None):
  QtGui.QWidget.__init__(self, parent)

  analyzeLayout = QtGui.QGridLayout()
  analyzeLayout.addWidget(data.canvas, 2, 0, 6, 8)

  self.setLayout(analyzeLayout)

if __name__ == "__main__":
   app = QtGui.QApplication(sys.argv)

   data = DataHolder()

   tabdialog = TabDialog()
   tabdialog.show()
   sys.exit(app.exec_())

Any suggestions are very much appreciated.



--
View this message in context: 
http://matplotlib.1069221.n5.nabble.com/Would-like-to-update-visible-plot-using-pyside-and-matplotlib-tp39576.html
Sent from the matplotlib - users mailing list archive at Nabble.com.

--
Everyone hates slow websites. So do we.
Make your web apps faster with AppDynamics
Download AppDynamics Lite for free today:
http://p.sf.net/sfu/appdyn_sfd2d_oct
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


Re: [Matplotlib-users] Histogram with overlapping bins

2012-10-22 Thread fiolj
Hi, some time ago I needed the same thing and hacked the function
histogram (from numpy or matplo. Here goes my function

## Calculates the histogram allowing for overlapping bins, which are
given by
#
# @param a
# @param bins a sequence of pairs (left,right), limits for each bin
#
# @return hist (numpy array)
# bin_centers (numpy array)
def myhistogram(a, bins):
  """
  Compute the histogram of a set of data.

  Parameters
  --
  a : array_like
  Input data.
  bins : sequence of pairs
  It defines the bin edges (left,right), allowing for non-uniform
bin widths.

  Returns
  ---
  hist : array
The values of the histogram. See `normed` and `weights` for a
description of the possible semantics.
  bin_centers : array of dtype float
Return the bin centers ``(length(hist))``.

  Notes
  -
  All but the last (righthand-most) bin is half-open.  In other words, if
  `bins` is::

[1, 2, 3, 4]

  then the first bin is ``[1, 2)`` (including 1, but excluding 2) and the
  second ``[2, 3)``.  The last bin, however, is ``[3, 4]``, which *includes*
  4.

  Examples
  
  >>> myhistogram([1,2,1], bins=[(0,1),(1,1.5),(1.5,2.5),(2,3)])
  (array([0.5, 1.25, 2, 2.5]), array([0, 0, 1, 2, 3]))
  """
  bins = np.asarray(bins)   # bins are 2-dimensional arrays
of shape (n,2)
  if len(bins.shape) != 2 or bins.shape[1] != 2:
raise AttributeError, 'bins must be a list/array of 2-tuples.'

  a = np.asarray(a)
  a =  a.ravel()
  n = np.zeros(len(bins), int)

  block = 65536
  for i in np.arange(0, len(a), block):
sa = np.sort(a[i:i+block])
n += np.r_[sa.searchsorted(bins[:-1,1], 'left'),
sa.searchsorted(bins[-1,1], 'right')]\
 - np.r_[sa.searchsorted(bins[:-1,0], 'left'),
sa.searchsorted(bins[-1,0], 'right')]
  return n, (bins[:,0]+bins[:,1])/2.

--
Everyone hates slow websites. So do we.
Make your web apps faster with AppDynamics
Download AppDynamics Lite for free today:
http://p.sf.net/sfu/appdyn_sfd2d_oct
___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users


[Matplotlib-users] time taken to savefig

2012-10-22 Thread Larry Cotton
Hi

I have been doing some work that generates a lot of plots and since the
plots were taking a long time I looked into to whether I could speed up the
process.

I found some information on how I might improve things from the following
link:
http://stackoverflow.com/questions/11688318/how-to-speed-up-matplotlib-when-plotting-and-saving-lots-of-figureswhich
showa that you can speed things up by using the same axes and simply
updating the line data.

When I adapted this idea to my plots I noticed that, though the plot loop
was quicker my script was running slower. I wrote a code snippet to repeat
the problem - shown below:
#!/usr/bin/env python
import os, matplotlib, time
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import numpy as np
from cmpactionresultsbetweenviews_1 import getPlotHtml

allActionPlotLists = [[0,  1,  2 ,  3, 4,  5,  6,  7, 8,  9],
  [ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
  [9,8,7,6,5,4,3,2,1,0],
  [19,18,17,16,15,14,13,12,11,10]]
allActionLegendsLists = [str(i) for i in range(len(allActionPlotLists[0]))]

legendProps={'labelspacing':0.5, 'prop':{'size':8}}
colours=['b+-', 'r+-', 'g+-', 'k+-', 'c+-', 'm+-', 'bD:', 'rD:', 'gD:',
'kD:']
fig = plt.figure()
ax = None
plotlines = [None for i in range(len(allActionPlotLists))]
savedir = "tmpRes"
if not os.path.exists(savedir):
os.makedirs(savedir)
figSrcFnRoot = "plotFil"
fil = open(os.path.join(savedir, "savepng.html"), 'w')

xlabel = "x label"
ylabel = "values"
colours=['b+-', 'r+-', 'g+-', 'k+-', 'c+-', 'm+-', 'bD:', 'rD:', 'gD:',
'kD:']

for i in range(20):
start_plot_time = time.time()
plottitle = "Plot %d" % (i)
fig.suptitle("")
fig.suptitle(plottitle)

for subPltIdx in range(len(allActionPlotLists)):
li = allActionPlotLists[subPltIdx]
if ax == None:
ax = fig.add_subplot(1,1,1)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)

if plotlines[subPltIdx] == None:
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
plotlines[subPltIdx] = ax.plot(range(len(li)), li,
colours[subPltIdx])[0]
else:
plotlines[subPltIdx].set_ydata(li)
plotlines[subPltIdx].set_xdata(range(len(li)))

fig.legend(plotlines, allActionLegendsLists, labelspacing=0.5,
prop=legendProps['prop'])
#  change the above line for the one below and the increasing save
time problem goes away
#ax.legend(plotlines, allActionLegendsLists, labelspacing=0.5,
prop=legendProps['prop'])
print "plot Execution time:", time.time()-start_plot_time

figfn = "%s_%d" % (figSrcFnRoot, i)
figfnlink = figfn.replace('%',
'%25').replace(';','%3b').replace(':','%3A')
fn = os.path.join(savedir, "%s.png" % figfn)
start_time = time.time()
fig.savefig(fn, format='png',dpi=75)
print "savefig Execution time:", time.time()-start_time
htmlStr = ''
htmlStr += '' % (os.path.join(".","%s.png" % figfnlink), figfn)
fil.write(htmlStr + "")
plt.close()
fil.close()

A little further investigation showed that savefig was taking longer each
run of the loop. I eventually noticed that replacing the call to
fig.legend() with ax.legend() solved the problem. Anyone know why the time
taken to save the plot increases when using fig.legend() in the code above ?

While doing this I also noticed a couple of other things:
1. I cannot seem to clear the figure title, so when I re-set it I get the
new title overlaying the old one in the plot output. Does anyone know how
to completely clear and reset the title of an existing figure ?

2. The call to figure.legend() puts the legends nicely outside the plot
boundaries (in the top right hand corner). The equivalent call to
ax.legend() places the legends inside the plot boundary. Does anyone know
a) why the behavior here is slightly different and b) how I can get the
legends outside the plot boundary using ax.legend() ?
--
Everyone hates slow websites. So do we.
Make your web apps faster with AppDynamics
Download AppDynamics Lite for free today:
http://p.sf.net/sfu/appdyn_sfd2d_oct___
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users