1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
|
"""
This example demonstrates the creation of a plot with
DateAxisItem and a customized ViewBox.
"""
import numpy as np
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore
class CustomViewBox(pg.ViewBox):
def __init__(self, *args, **kwds):
kwds['enableMenu'] = False
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.MouseButton.RightButton:
self.autoRange()
## reimplement mouseDragEvent to disable continuous axis zoom
def mouseDragEvent(self, ev, axis=None):
if axis is not None and ev.button() == QtCore.Qt.MouseButton.RightButton:
ev.ignore()
else:
pg.ViewBox.mouseDragEvent(self, ev, axis=axis)
class CustomTickSliderItem(pg.TickSliderItem):
def __init__(self, *args, **kwds):
pg.TickSliderItem.__init__(self, *args, **kwds)
self.all_ticks = {}
self._range = [0,1]
def setTicks(self, ticks):
for tick, pos in self.listTicks():
self.removeTick(tick)
for pos in ticks:
tickItem = self.addTick(pos, movable=False, color="#333333")
self.all_ticks[pos] = tickItem
self.updateRange(None, self._range)
def updateRange(self, vb, viewRange):
origin = self.tickSize/2.
length = self.length
lengthIncludingPadding = length + self.tickSize + 2
self._range = viewRange
for pos in self.all_ticks:
tickValueIncludingPadding = (pos - viewRange[0]) / (viewRange[1] - viewRange[0])
tickValue = (tickValueIncludingPadding*lengthIncludingPadding - origin) / length
# Convert from np.bool_ to bool for setVisible
visible = bool(tickValue >= 0 and tickValue <= 1)
tick = self.all_ticks[pos]
tick.setVisible(visible)
if visible:
self.setTickValue(tick, tickValue)
app = pg.mkQApp()
axis = pg.DateAxisItem(orientation='bottom')
vb = CustomViewBox()
pw = pg.PlotWidget(viewBox=vb, axisItems={'bottom': axis}, enableMenu=False, title="PlotItem with DateAxisItem, custom ViewBox and markers on x axis<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')
# Using allowAdd and allowRemove to limit user interaction
tickViewer = CustomTickSliderItem(allowAdd=False, allowRemove=False)
vb.sigXRangeChanged.connect(tickViewer.updateRange)
pw.plotItem.layout.addItem(tickViewer, 4, 1)
tickViewer.setTicks( [dates[0], dates[2], dates[-1]] )
pw.show()
pw.setWindowTitle('pyqtgraph example: customPlot')
r = pg.PolyLineROI([(0,0), (10, 10)])
pw.addItem(r)
if __name__ == '__main__':
pg.exec()
|