Commit 662b319d authored by Luke Campagnola's avatar Luke Campagnola
Browse files

- PlotItem can now be constructed with customized ViewBox and AxisItems

- Text spacing fix for AxisItem
parent f178919b
......@@ -505,18 +505,19 @@ class GraphicsScene(QtGui.QGraphicsScene):
menusToAdd = []
while item is not self:
item = item.parentItem()
if item is None:
item = self
if not hasattr(item, "getContextMenus"):
continue
subMenus = item.getContextMenus(event)
if subMenus is None:
continue
if type(subMenus) is not list: ## so that some items (like FlowchartViewBox) can return multiple menus
subMenus = [subMenus]
for sm in subMenus:
menusToAdd.append(sm)
......
......@@ -49,10 +49,10 @@ def getConfigOption(opt):
def systemInfo():
print "sys.platform:", sys.platform
print "sys.version:", sys.version
print("sys.platform: %s" % sys.platform)
print("sys.version: %s" % sys.version)
from .Qt import VERSION_INFO
print "qt bindings:", VERSION_INFO
print("qt bindings: %s" % VERSION_INFO)
global REVISION
if REVISION is None: ## this code was probably checked out from bzr; look up the last-revision file
......@@ -60,8 +60,8 @@ def systemInfo():
if os.path.exists(lastRevFile):
REVISION = open(lastRevFile, 'r').read().strip()
print "pyqtgraph:", REVISION
print "config:"
print("pyqtgraph: %s" % REVISION)
print("config:")
import pprint
pprint.pprint(CONFIG_OPTIONS)
......@@ -126,7 +126,7 @@ def importAll(path, excludes=()):
globals()[k] = getattr(mod, k)
importAll('graphicsItems')
importAll('widgets', excludes=['MatplotlibWidget'])
importAll('widgets', excludes=['MatplotlibWidget', 'RemoteGraphicsView'])
from .imageview import *
from .WidgetGroup import *
......
......@@ -16,6 +16,7 @@ examples = OrderedDict([
('Video speed test', 'VideoSpeedTest.py'),
('Plot speed test', 'PlotSpeedTest.py'),
('Data Slicing', 'DataSlicing.py'),
('Plot Customization', 'customPlot.py'),
('GraphicsItems', OrderedDict([
('Scatter Plot', 'ScatterPlot.py'),
#('PlotItem', 'PlotItem.py'),
......@@ -45,7 +46,7 @@ examples = OrderedDict([
#('VerticalLabel', '../widgets/VerticalLabel.py'),
('JoystickButton', 'JoystickButton.py'),
])),
('GraphicsScene', 'GraphicsScene.py'),
('Flowcharts', 'Flowchart.py'),
#('Canvas', '../canvas'),
......
# -*- coding: utf-8 -*-
##
## This example demonstrates the creation of a plot with a customized
## AxisItem and ViewBox.
##
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
import time
class DateAxis(pg.AxisItem):
def tickStrings(self, values, scale, spacing):
return [time.strftime('%b %Y', time.localtime(x)) for x in values]
class CustomViewBox(pg.ViewBox):
def __init__(self, *args, **kwds):
pg.ViewBox.__init__(self, *args, **kwds)
self.setMouseMode(self.RectMode)
## reimplement right-click to zoom out
def mouseClickEvent(self, ev):
if ev.button() == QtCore.Qt.RightButton:
self.autoRange()
def mouseDragEvent(self, ev):
if ev.button() == QtCore.Qt.RightButton:
ev.ignore()
else:
pg.ViewBox.mouseDragEvent(self, ev)
app = pg.mkQApp()
axis = DateAxis(orientation='bottom')
vb = CustomViewBox()
pw = pg.PlotWidget(viewBox=vb, axisItems={'bottom': axis}, enableMenu=False, title="PlotItem with custom axis and ViewBox<br>Menu disabled, mouse behavior changed: left-drag to zoom, right-click to reset zoom")
dates = np.arange(8) * (3600*24*356)
pw.plot(x=dates, y=[1,6,2,4,3,5,6,8], symbol='o')
pw.show()
r = pg.PolyLineROI([(0,0), (10, 10)])
pw.addItem(r)
## Start Qt event loop unless running in interactive mode or using pyside.
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()
......@@ -363,6 +363,29 @@ class AxisItem(GraphicsWidget):
(intervals[minorIndex], 0)
]
##### This does not work -- switching between 2/5 confuses the automatic text-level-selection
### Determine major/minor tick spacings which flank the optimal spacing.
#intervals = np.array([1., 2., 5., 10., 20., 50., 100.]) * p10unit
#minorIndex = 0
#while intervals[minorIndex+1] <= optimalSpacing:
#minorIndex += 1
### make sure we never see 5 and 2 at the same time
#intIndexes = [
#[0,1,3],
#[0,2,3],
#[2,3,4],
#[3,4,6],
#[3,5,6],
#][minorIndex]
#return [
#(intervals[intIndexes[2]], 0),
#(intervals[intIndexes[1]], 0),
#(intervals[intIndexes[0]], 0)
#]
def tickValues(self, minVal, maxVal, size):
"""
......@@ -395,7 +418,7 @@ class AxisItem(GraphicsWidget):
## remove any ticks that were present in higher levels
## we assume here that if the difference between a tick value and a previously seen tick value
## is less than spacing/100, then they are 'equal' and we can ignore the new tick.
values = filter(lambda x: all(np.abs(allValues-x) > spacing*0.01), values)
values = list(filter(lambda x: all(np.abs(allValues-x) > spacing*0.01), values) )
allValues = np.concatenate([allValues, values])
ticks.append((spacing, values))
......@@ -601,9 +624,9 @@ class AxisItem(GraphicsWidget):
if tickPositions[i][j] is None:
strings[j] = None
textRects.extend([p.boundingRect(QtCore.QRectF(0, 0, 100, 100), QtCore.Qt.AlignCenter, s) for s in strings if s is not None])
if i > 0: ## always draw top level
## measure all text, make sure there's enough room
textRects.extend([p.boundingRect(QtCore.QRectF(0, 0, 100, 100), QtCore.Qt.AlignCenter, s) for s in strings if s is not None])
if axis == 0:
textSize = np.sum([r.height() for r in textRects])
else:
......@@ -613,7 +636,6 @@ class AxisItem(GraphicsWidget):
textFillRatio = float(textSize) / lengthInPixels
if textFillRatio > 0.7:
break
#spacing, values = tickLevels[best]
#strings = self.tickStrings(values, self.scale, spacing)
for j in range(len(strings)):
......
This diff is collapsed.
......@@ -62,7 +62,7 @@ class ViewBox(GraphicsWidget):
NamedViews = weakref.WeakValueDictionary() # name: ViewBox
AllViews = weakref.WeakKeyDictionary() # ViewBox: None
def __init__(self, parent=None, border=None, lockAspect=False, enableMouse=True, invertY=False, enableMenu = True, name=None):
def __init__(self, parent=None, border=None, lockAspect=False, enableMouse=True, invertY=False, enableMenu=True, name=None):
"""
============= =============================================================
**Arguments**
......@@ -136,7 +136,7 @@ class ViewBox(GraphicsWidget):
## Make scale box that is shown when dragging on the view
self.rbScaleBox = QtGui.QGraphicsRectItem(0, 0, 1, 1)
self.rbScaleBox.setPen(fn.mkPen((255,0,0), width=1))
self.rbScaleBox.setPen(fn.mkPen((255,255,100), width=1))
self.rbScaleBox.setBrush(fn.mkBrush(255,255,0,100))
self.rbScaleBox.hide()
self.addItem(self.rbScaleBox)
......@@ -358,7 +358,7 @@ class ViewBox(GraphicsWidget):
changes[1] = yRange
if len(changes) == 0:
print rect
print(rect)
raise Exception("Must specify at least one of rect, xRange, or yRange. (gave rect=%s)" % str(type(rect)))
changed = [False, False]
......@@ -863,7 +863,10 @@ class ViewBox(GraphicsWidget):
return self._menuCopy
def getContextMenus(self, event):
return self.menu.subMenus()
if self.menuEnabled():
return self.menu.subMenus()
else:
return None
#return [self.getMenu(event)]
......
......@@ -41,6 +41,8 @@ class PlotWidget(GraphicsView):
other methods, use :func:`getPlotItem <pyqtgraph.PlotWidget.getPlotItem>`.
"""
def __init__(self, parent=None, **kargs):
"""When initializing PlotWidget, all keyword arguments except *parent* are passed
to :func:`PlotItem.__init__() <pyqtgraph.PlotItem.__init__>`."""
GraphicsView.__init__(self, parent)
self.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
self.enableMouse(False)
......
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