在pyqtgraph中的x轴上显示字符串值

问题描述 投票:7回答:2

我想在pyqtgraph中显示x轴上刻度的字符串值。现在我无法弄清楚如何做到这一点。

例如:

x = ['a', 'b', 'c', 'd', 'e', 'f']
y = [1, 2, 3, 4, ,5, 6]
pg.plot(x, y) 

当我尝试将字符串数组传递给x变量时,它会尝试将其转换为float并使用错误消息中断GUI。

python qt pyqt pyqt4 pyqtgraph
2个回答
10
投票

通常在pyqtgraph中处理自定义轴字符串时,人们将子类化为AxisItem并使用他们想要显示的字符串覆盖tickStrings

参见例如pyqtgraph : how to plot time series (date and time on the x axis)?

Pyqtgraphs axisitem还有一个内置的setTicks,允许你指定要显示的刻度,这可以用于这样的简单问题而不是子类化AxisItem。


在x轴上使用自定义字符串绘图可以像这样完成。

  • 创建一个带有x值的dict以及要在轴上显示的字符串。

xdict = {0:'a', 1:'b', 2:'c', 3:'d', 4:'e', 5:'f'}

或者通过使用

x = ['a', 'b', 'c', 'd', 'e', 'f']
xdict = dict(enumerate(x))
  • 在AxisItem或Subclass AxisItem中使用setTicks,在tickStrings中查找与该值对应的字符串。

1.使用标准pyqtgraph AxisItem和setTicks

    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_()

屏幕截图来自示例:Screenshot from example


4
投票

我发现最简单的方法是准备一个索引列表和一个字符串列表,然后将它们组合在一起zip

ticks = [list(zip(range(5), ('a', 'b', 'c', 'd', 'e')))]

您可以获得PlotWidget的现有AxisItem,如下所示:

pw = pg.PlotWidget()
xax = pw.getAxis('bottom')

最后像这样设置轴的刻度:

xax.setTicks(ticks)

据我所知,PlotWidgets自动包含'底部'和'左'AxisItems,但如果您愿意,您可以创建和添加其他。

© www.soinside.com 2019 - 2024. All rights reserved.