from PyQt4 import QtCore
import pyqtgraph as pg
x = ['a', 'b', 'c', 'd', 'e', 'f']
y = [1, 2, 3, 4, 5, 6]
xdict = dict(enumerate(x))
win = pg.GraphicsWindow()
stringaxis = pg.AxisItem(orientation='bottom')
stringaxis.setTicks([xdict.items()])
plot = win.addPlot(axisItems={'bottom': stringaxis})
curve = plot.plot(list(xdict.keys()),y)
if __name__ == '__main__':
import sys
if sys.flags.interactive != 1 or not hasattr(QtCore, 'PYQT_VERSION'):
pg.QtGui.QApplication.exec_()
2。通过子类化AxisItem实现
这是一种更通用的方法,可以很容易地更改为各种有趣的事情,例如将unix时间戳转换为日期。
from PyQt4 import QtCore
import pyqtgraph as pg
import numpy as np
class MyStringAxis(pg.AxisItem):
def __init__(self, xdict, *args, **kwargs):
pg.AxisItem.__init__(self, *args, **kwargs)
self.x_values = np.asarray(xdict.keys())
self.x_strings = xdict.values()
def tickStrings(self, values, scale, spacing):
strings = []
for v in values:
# vs is the original tick value
vs = v * scale
# if we have vs in our values, show the string
# otherwise show nothing
if vs in self.x_values:
# Find the string with x_values closest to vs
vstr = self.x_strings[np.abs(self.x_values-vs).argmin()]
else:
vstr = ""
strings.append(vstr)
return strings
x = ['a', 'b', 'c', 'd', 'e', 'f']
y = [1, 2, 3, 4, 5, 6]
xdict = dict(enumerate(x))
win = pg.GraphicsWindow()
stringaxis = MyStringAxis(xdict, orientation='bottom')
plot = win.addPlot(axisItems={'bottom': stringaxis})
curve = plot.plot(list(xdict.keys()),y)
if __name__ == '__main__':
import sys
if sys.flags.interactive != 1 or not hasattr(QtCore, 'PYQT_VERSION'):
pg.QtGui.QApplication.exec_()
我发现最简单的方法是准备一个索引列表和一个字符串列表,然后将它们放在一起:
您可以获取PlotWidget的现有AxisItem,如下所示:
最后设置轴的刻度如下:
据我所知,PlotWidgets自动包含“bottom”和“left”轴项,但如果需要,可以创建和添加其他轴项。
通常在pyqtgraph中,当处理自定义轴字符串时,人们会将AxisItem子类化,并用希望显示的字符串重写tickStrings。
参见例如pyqtgraph : how to plot time series (date and time on the x axis)?
Pyqtgraphs axisitem还有一个内置的setTicks允许您指定将要显示的标记,这可以针对这样一个简单的问题来完成,而不是对axisitem进行子类化。
可以这样在x轴上使用自定义字符串绘制。
xdict = {0:'a', 1:'b', 2:'c', 3:'d', 4:'e', 5:'f'}
或者通过使用
一。使用标准pyqtgraph axistem和setTicks
2。通过子类化AxisItem实现
这是一种更通用的方法,可以很容易地更改为各种有趣的事情,例如将unix时间戳转换为日期。
示例截图:
相关问题 更多 >
编程相关推荐