Commit 194eba1e authored by Luke Campagnola's avatar Luke Campagnola
Browse files

merge from inp

parents 4c887c8f 63c3b36a
......@@ -10,5 +10,7 @@ Contents:
graphicsItems/index
widgets/index
3dgraphics/index
colormap
parametertree/index
graphicsscene/index
flowchart/index
ColorMap
========
.. autoclass:: pyqtgraph.ColorMap
:members:
.. automethod:: pyqtgraph.ColorMap.__init__
......@@ -91,6 +91,8 @@ Mesh Generation Functions
Miscellaneous Functions
-----------------------
.. autofunction:: pyqtgraph.arrayToQPath
.. autofunction:: pyqtgraph.pseudoScatter
.. autofunction:: pyqtgraph.systemInfo
......
GraphItem
=========
.. autoclass:: pyqtgraph.GraphItem
:members:
.. automethod:: pyqtgraph.GraphItem.__init__
......@@ -12,6 +12,7 @@ Contents:
plotdataitem
plotitem
imageitem
graphitem
viewbox
linearregionitem
infiniteline
......
......@@ -15,6 +15,7 @@ Contents:
mouse_interaction
how_to_use
installation
qtcrashcourse
plotting
images
3dgraphics
......
......@@ -3,20 +3,76 @@ Qt Crash Course
Pyqtgraph makes extensive use of Qt for generating nearly all of its visual output and interfaces. Qt's documentation is very well written and we encourage all pyqtgraph developers to familiarize themselves with it. The purpose of this section is to provide an introduction to programming with Qt (using either PyQt or PySide) for the pyqtgraph developer.
QWidgets and Layouts
--------------------
A Qt GUI is almost always composed of a few basic components:
* A window. This is often provided by QMainWindow, but note that all QWidgets can be displayed in their window by simply calling widget.show() if the widget does not have a parent.
* Multiple QWidget instances such as QPushButton, QLabel, QComboBox, etc.
* QLayout instances (optional, but strongly encouraged) which automatically manage the positioning of widgets to allow the GUI to resize in a usable way.
Pyqtgraph fits into this scheme by providing its own QWidget subclasses to be inserted into your GUI.
Example::
from PyQt4 import QtGui # (the example applies equally well to PySide)
import pyqtgraph as pg
## Always start by initializing Qt (only once per application)
app = QtGui.QApplication([])
## Define a top-level widget to hold everything
w = QtGui.QWidget()
## Create some widgets to be placed inside
btn = QtGui.QPushButton('press me')
text = QtGui.QLineEdit('enter text')
listw = QtGui.QListWidget()
plot = pg.PlotWidget()
## Create a grid layout to manage the widgets size and position
layout = QtGui.QGridLayout()
w.setLayout(layout)
## Add widgets to the layout in their proper positions
layout.addWidget(btn, 0, 0) # button goes in upper-left
layout.addWidget(text, 1, 0) # text edit goes in middle-left
layout.addWidget(listw, 2, 0) # list widget goes in bottom-left
layout.addWidget(plot, 0, 1, 3, 1) # plot goes on right side, spanning 3 rows
## Display the widget as a new window
w.show()
## Start the Qt event loop
app.exec_()
More complex interfaces may be designed graphically using Qt Designer, which allows you to simply drag widgets into your window to define its appearance.
Naming Conventions
------------------
Virtually every class in pyqtgraph is an extension of base classes provided by Qt. When reading the documentation, remember that all of Qt's classes start with the letter 'Q', whereas pyqtgraph's classes do not. When reading through the methods for any class, it is often helpful to see which Qt base classes are used and look through the Qt documentation as well.
Most of Qt's classes define signals which can be difficult to tell apart from regular methods. Almost all signals explicity defined by pyqtgraph are named beginning with 'sig' to indicate that these signals are not defined at the Qt level.
In most cases, classes which end in 'Widget' are subclassed from QWidget and can therefore be used as a GUI element in a Qt window. Classes which end in 'Item' are subclasses of QGraphicsItem and can only be displayed within a QGraphicsView instance (such as GraphicsLayoutWidget or PlotWidget).
Signals, Slots, and Events
--------------------------
[ to be continued.. please post a request on the pyqtgraph forum if you'd like to read more ]
GraphicsView and GraphicsItems
------------------------------
Coordinate Systems
------------------
Coordinate Systems and Transformations
--------------------------------------
Mouse and Keyboard Input
......@@ -26,3 +82,7 @@ Mouse and Keyboard Input
QTimer, the Event Loop, and Multi-Threading
-------------------------------------------
Multi-threading vs Multi-processing in Qt
-----------------------------------------
ColorMapWidget
==============
.. autoclass:: pyqtgraph.ColorMapWidget
:members:
.. automethod:: pyqtgraph.ColorMapWidget.__init__
.. automethod:: pyqtgraph.widgets.ColorMapWidget.ColorMapParameter.setFields
.. automethod:: pyqtgraph.widgets.ColorMapWidget.ColorMapParameter.map
\ No newline at end of file
......@@ -17,6 +17,8 @@ Contents:
gradientwidget
histogramlutwidget
parametertree
colormapwidget
scatterplotwidget
graphicsview
rawimagewidget
datatreewidget
......
ScatterPlotWidget
=================
.. autoclass:: pyqtgraph.ScatterPlotWidget
:members:
.. automethod:: pyqtgraph.ScatterPlotWidget.__init__
# -*- coding: utf-8 -*-
"""
Demonstrates basic use of ErrorBarItem
"""
import initExample ## Add path to library (just for examples; you do not need this)
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui
import numpy as np
import pyqtgraph as pg
import numpy as np
pg.setConfigOptions(antialias=True)
x = np.arange(10)
y = np.arange(10) %3
top = np.linspace(1.0, 3.0, 10)
bottom = np.linspace(2, 0.5, 10)
plt = pg.plot()
err = pg.ErrorBarItem(x=x, y=y, top=top, bottom=bottom, beam=0.5)
plt.addItem(err)
plt.plot(x, y, symbol='o', pen={'color': 0.8, 'width': 2})
## Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()
# -*- coding: utf-8 -*-
## This example demonstrates many of the 2D plotting capabilities
## in pyqtgraph. All of the plots may be panned/scaled by dragging with
## the left/right mouse buttons. Right click on any plot to show a context menu.
import initExample ## Add path to library (just for examples; you do not need this)
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import pyqtgraph as pg
#QtGui.QApplication.setGraphicsSystem('raster')
app = QtGui.QApplication([])
#mw = QtGui.QMainWindow()
#mw.resize(800,800)
win = pg.GraphicsWindow(title="Basic plotting examples")
win.resize(1000,600)
p5 = win.addPlot(title="Scatter plot, axis labels, log scale")
x = np.random.normal(size=1000) * 1e-5
y = x*1000 + 0.005 * np.random.normal(size=1000)
y -= y.min()-1.0
mask = x > 1e-15
x = x[mask]
y = y[mask]
p5.plot(x, y, pen=None, symbol='t', symbolPen=None, symbolSize=10, symbolBrush=(100, 100, 255, 50))
p5.setLabel('left', "Y Axis", units='A')
p5.setLabel('bottom', "Y Axis", units='s')
p5.setLogMode(x=True, y=False)
## Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()
......@@ -59,7 +59,6 @@ pos = np.random.normal(size=(2,n), scale=1e-5)
spots = [{'pos': pos[:,i], 'data': 1, 'brush':pg.intColor(i, n), 'symbol': i%5, 'size': 5+i/10.} for i in range(n)]
s2.addPoints(spots)
w2.addItem(s2)
w2.setRange(s2.boundingRect())
s2.sigClicked.connect(clicked)
......@@ -71,7 +70,7 @@ s3 = pg.ScatterPlotItem(pxMode=False) ## Set pxMode=False to allow spots to tr
spots3 = []
for i in range(10):
for j in range(10):
spots3.append({'pos': (1e-6*i, 1e-6*j), 'size': 1e-6, 'brush':pg.intColor(i*10+j, 100)})
spots3.append({'pos': (1e-6*i, 1e-6*j), 'size': 1e-6, 'pen': {'color': 'w', 'width': 2}, 'brush':pg.intColor(i*10+j, 100)})
s3.addPoints(spots3)
w3.addItem(s3)
s3.sigClicked.connect(clicked)
......
import initExample ## Add path to library (just for examples; you do not need this)
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
import numpy as np
pg.plot(np.random.normal(size=100000), title="Simplest possible plotting example")
## Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
import sys
if sys.flags.interactive != 1 or not hasattr(QtCore, 'PYQT_VERSION'):
pg.QtGui.QApplication.exec_()
......@@ -27,6 +27,8 @@ examples = OrderedDict([
('Scatter Plot', 'ScatterPlot.py'),
#('PlotItem', 'PlotItem.py'),
('IsocurveItem', 'isocurve.py'),
('GraphItem', 'GraphItem.py'),
('ErrorBarItem', 'ErrorBarItem.py'),
('ImageItem - video', 'ImageItem.py'),
('ImageItem - draw', 'Draw.py'),
('Region-of-Interest', 'ROIExamples.py'),
......
# -*- coding: utf-8 -*-
import initExample ## Add path to library (just for examples; you do not need this)
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np
app = pg.mkQApp()
plt = pg.PlotWidget()
app.processEvents()
## Putting this at the beginning or end does not have much effect
plt.show()
## The auto-range is recomputed after each item is added,
## so disabling it before plotting helps
plt.enableAutoRange(False, False)
def plot():
start = pg.ptime.time()
n = 15
pts = 100
x = np.linspace(0, 0.8, pts)
y = np.random.random(size=pts)*0.8
for i in xrange(n):
for j in xrange(n):
## calling PlotWidget.plot() generates a PlotDataItem, which
## has a bit more overhead than PlotCurveItem, which is all
## we need here. This overhead adds up quickly and makes a big
## difference in speed.
#plt.plot(x=x+i, y=y+j)
plt.addItem(pg.PlotCurveItem(x=x+i, y=y+j))
#path = pg.arrayToQPath(x+i, y+j)
#item = QtGui.QGraphicsPathItem(path)
#item.setPen(pg.mkPen('w'))
#plt.addItem(item)
dt = pg.ptime.time() - start
print "Create plots took: %0.3fms" % (dt*1000)
## Plot and clear 5 times, printing the time it took
for i in range(5):
plt.clear()
plot()
app.processEvents()
plt.autoRange()
def fastPlot():
## Different approach: generate a single item with all data points.
## This runs about 20x faster.
start = pg.ptime.time()
n = 15
pts = 100
x = np.linspace(0, 0.8, pts)
y = np.random.random(size=pts)*0.8
xdata = np.empty((n, n, pts))
xdata[:] = x.reshape(1,1,pts) + np.arange(n).reshape(n,1,1)
ydata = np.empty((n, n, pts))
ydata[:] = y.reshape(1,1,pts) + np.arange(n).reshape(1,n,1)
conn = np.ones((n*n,pts))
conn[:,-1] = False # make sure plots are disconnected
path = pg.arrayToQPath(xdata.flatten(), ydata.flatten(), conn.flatten())
item = QtGui.QGraphicsPathItem(path)
item.setPen(pg.mkPen('w'))
plt.addItem(item)
dt = pg.ptime.time() - start
print "Create plots took: %0.3fms" % (dt*1000)
## Plot and clear 5 times, printing the time it took
if hasattr(pg, 'arrayToQPath'):
for i in range(5):
plt.clear()
fastPlot()
app.processEvents()
else:
print "Skipping fast tests--arrayToQPath function is missing."
plt.autoRange()
## Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()
......@@ -117,7 +117,7 @@ class GraphicsScene(QtGui.QGraphicsScene):
def render(self, *args):
self.prepareForPaint()
return QGraphicsScene.render(self, *args)
return QtGui.QGraphicsScene.render(self, *args)
def prepareForPaint(self):
"""Called before every render. This method will inform items that the scene is about to
......
......@@ -4,7 +4,7 @@ PyQtGraph - Scientific Graphics and GUI Library for Python
www.pyqtgraph.org
"""
__version__ = '0.9.5'
__version__ = None
### import all the goodies and add some helper functions for easy CLI use
......@@ -187,6 +187,7 @@ from .SRTTransform3D import SRTTransform3D
from .functions import *
from .graphicsWindows import *
from .SignalProxy import *
from .colormap import *
from .ptime import time
......
......@@ -3,6 +3,25 @@ import scipy.interpolate
from pyqtgraph.Qt import QtGui, QtCore
class ColorMap(object):
"""
A ColorMap defines a relationship between a scalar value and a range of colors.
ColorMaps are commonly used for false-coloring monochromatic images, coloring
scatter-plot points, and coloring surface plots by height.
Each color map is defined by a set of colors, each corresponding to a
particular scalar value. For example:
| 0.0 -> black
| 0.2 -> red
| 0.6 -> yellow
| 1.0 -> white
The colors for intermediate values are determined by interpolating between
the two nearest colors in either RGB or HSV color space.
To provide user-defined color mappings, see :class:`GradientWidget <pyqtgraph.GradientWidget>`.
"""
## color interpolation modes
RGB = 1
......@@ -54,7 +73,16 @@ class ColorMap(object):
def map(self, data, mode='byte'):
"""
Return an array of colors corresponding to the values in *data*.
Data must be either a scalar position or an array (any shape) of positions.
The *mode* argument determines the type of data returned:
=========== ===============================================================
byte (default) Values are returned as 0-255 unsigned bytes.
float Values are returned as 0.0-1.0 floats.
qcolor Values are returned as an array of QColor objects.
=========== ===============================================================
"""
if isinstance(mode, basestring):
mode = self.enumMap[mode.lower()]
......@@ -80,16 +108,19 @@ class ColorMap(object):
return interp
def mapToQColor(self, data):
"""Convenience function; see :func:`map() <pyqtgraph.ColorMap.map>`."""
return self.map(data, mode=self.QCOLOR)
def mapToByte(self, data):
"""Convenience function; see :func:`map() <pyqtgraph.ColorMap.map>`."""
return self.map(data, mode=self.BYTE)
def mapToFloat(self, data):
"""Convenience function; see :func:`map() <pyqtgraph.ColorMap.map>`."""
return self.map(data, mode=self.FLOAT)
def getGradient(self, p1=None, p2=None):
"""Return a QLinearGradient object."""
"""Return a QLinearGradient object spanning from QPoints p1 to p2."""
if p1 == None:
p1 = QtCore.QPointF(0,0)
if p2 == None:
......@@ -119,7 +150,7 @@ class ColorMap(object):
return g
def getColors(self, mode=None):
"""Return list of all colors converted to the specified mode.
"""Return list of all color stops converted to the specified mode.
If mode is None, then no conversion is done."""
if isinstance(mode, basestring):
mode = self.enumMap[mode.lower()]
......@@ -158,75 +189,19 @@ class ColorMap(object):
self.stopsCache[mode] = (self.pos, color)
return self.stopsCache[mode]
#def getColor(self, x, toQColor=True):
#"""
#Return a color for a given value.
#============= ==================================================================
#**Arguments**
#x Value (position on gradient) of requested color.
#toQColor If true, returns a QColor object, else returns a (r,g,b,a) tuple.
#============= ==================================================================
#"""
#ticks = self.listTicks()
#if x <= ticks[0][1]:
#c = ticks[0][0].color
#if toQColor:
#return QtGui.QColor(c) # always copy colors before handing them out
#else:
#return (c.red(), c.green(), c.blue(), c.alpha())
#if x >= ticks[-1][1]:
#c = ticks[-1][0].color
#if toQColor:
#return QtGui.QColor(c) # always copy colors before handing them out
#else:
#return (c.red(), c.green(), c.blue(), c.alpha())
#x2 = ticks[0][1]
#for i in range(1,len(ticks)):
#x1 = x2
#x2 = ticks[i][1]
#if x1 <= x and x2 >= x:
#break
#dx = (x2-x1)
#if dx == 0:
#f = 0.
#else:
#f = (x-x1) / dx
#c1 = ticks[i-1][0].color
#c2 = ticks[i][0].color
#if self.colorMode == 'rgb':
#r = c1.red() * (1.-f) + c2.red() * f
#g = c1.green() * (1.-f) + c2.green() * f
#b = c1.blue() * (1.-f) + c2.blue() * f
#a = c1.alpha() * (1.-f) + c2.alpha() * f
#if toQColor:
#return QtGui.QColor(int(r), int(g), int(b), int(a))
#else:
#return (r,g,b,a)
#elif self.colorMode == 'hsv':
#h1,s1,v1,_ = c1.getHsv()
#h2,s2,v2,_ = c2.getHsv()
#h = h1 * (1.-f) + h2 * f
#s = s1 * (1.-f) + s2 * f
#v = v1 * (1.-f) + v2 * f
#c = QtGui.QColor()
#c.setHsv(h,s,v)
#if toQColor:
#return c
#else:
#return (c.red(), c.green(), c.blue(), c.alpha())
def getLookupTable(self, start=0.0, stop=1.0, nPts=512, alpha=None, mode='byte'):
"""
Return an RGB(A) lookup table (ndarray).
============= ============================================================================
**Arguments**
nPts The number of points in the returned lookup table.
alpha True, False, or None - Specifies whether or not alpha values are included
in the table. If alpha is None, it will be automatically determined.
start The starting value in the lookup table (default=0.0)
stop The final value in the lookup table (default=1.0)
nPts The number of points in the returned lookup table.
alpha True, False, or None - Specifies whether or not alpha values are included
in the table. If alpha is None, it will be automatically determined.
mode Determines return type: 'byte' (0-255), 'float' (0.0-1.0), or 'qcolor'.
See :func:`map() <pyqtgraph.ColorMap.map>`.
============= ============================================================================
"""
if isinstance(mode, basestring):
......@@ -249,7 +224,9 @@ class ColorMap(object):
return np.any(self.color[:,3] != max)
def isMapTrivial(self):
"""Return True if the gradient has exactly two stops in it: black at 0.0 and white at 1.0"""
"""
Return True if the gradient has exactly two stops in it: black at 0.0 and white at 1.0.
"""
if len(self.pos) != 2:
return False
if self.pos[0] != 0.0 or self.pos[1] != 1.0:
......
......@@ -66,7 +66,7 @@ class Exporter(object):
if selectedExt is not None:
selectedExt = selectedExt.groups()[0].lower()
if ext != selectedExt:
fileName = fileName + selectedExt
fileName = fileName + '.' + selectedExt.lstrip('.')
self.export(fileName=fileName, **self.fileDialog.opts)
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment