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

2024-03-29 11:15:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在pyqtgraph中显示x轴上刻度的字符串值。现在我不知道怎么做。

例如:

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

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


Tags: 字符串消息plot错误gui数组floatpyqtgraph
2条回答

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

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

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

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

最后设置轴的刻度如下:

xax.setTicks(ticks)

据我所知,PlotWidgets自动包含“bottom”和“left”轴项,但如果需要,可以创建和添加其他轴项。

通常在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中使用设置记号 子类AxisItem并在tickStrings中找到与该值对应的字符串。

一。使用标准pyqtgraph axistem和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

相关问题 更多 >