cod*_*006 7 python qt pyqt pyqt4 pyqtgraph
我想在x轴上显示刻度的字符串值pyqtgraph.现在我无法弄清楚如何做到这一点.
例如:
x = ['a', 'b', 'c', 'd', 'e', 'f']
y = [1, 2, 3, 4, ,5, 6]
pg.plot(x, y)
Run Code Online (Sandbox Code Playgroud)
当我尝试将字符串数组传递给x变量时,它会尝试将其转换为float并使用错误消息中断GUI.
lud*_*dek 10
通常在pyqtgraph中处理自定义轴字符串时,人们将子类化为AxisItem,并使用他们想要显示的字符串覆盖tickStrings.
参见例如pyqtgraph:如何绘制时间序列(x轴上的日期和时间)?
Pyqtgraphs axisitem还有一个内置的setTicks,允许你指定要显示的刻度,这可以用于这样的简单问题而不是子类化AxisItem.
在x轴上使用自定义字符串绘图可以像这样完成.
xdict = {0:'a', 1:'b', 2:'c', 3:'d', 4:'e', 5:'f'}
或者通过使用
x = ['a', 'b', 'c', 'd', 'e', 'f']
xdict = dict(enumerate(x))
Run Code Online (Sandbox Code Playgroud)
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_()
Run Code Online (Sandbox Code Playgroud)
这是一种更通用的方法,可以轻松更改为各种有趣的事物,例如将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_()
Run Code Online (Sandbox Code Playgroud)
我发现准备索引列表和字符串列表,然后将zip它们在一起最简单:
ticks = [list(zip(range(5), ('a', 'b', 'c', 'd', 'e')))]
Run Code Online (Sandbox Code Playgroud)
您可以像这样获得PlotWidget的现有AxisItem:
pw = pg.PlotWidget()
xax = pw.getAxis('bottom')
Run Code Online (Sandbox Code Playgroud)
最后像这样设置轴的刻度:
xax.setTicks(ticks)
Run Code Online (Sandbox Code Playgroud)
据我所知,PlotWidgets自动包含“底部”和“左侧” AxisItem,但是您可以根据需要创建和添加其他项。
| 归档时间: |
|
| 查看次数: |
8004 次 |
| 最近记录: |