Pyqtgraph: 为绘图中的线条添加图例

10

我正在使用pyqtgraph,想要在图例中添加一个InfiniteLines的项目。

我已经修改了示例代码以进行演示:

# -*- coding: utf-8 -*-
"""
Demonstrates basic use of LegendItem

"""
import initExample ## Add path to library (just for examples; you do not need this)

import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui

plt = pg.plot()
plt.setWindowTitle('pyqtgraph example: Legend')
plt.addLegend()

c1 = plt.plot([1,3,2,4], pen='r', name='red plot')
c2 = plt.plot([2,1,4,3], pen='g', fillLevel=0, fillBrush=(255,255,255,30), name='green plot')
c3 = plt.addLine(y=4, pen='y')
# TODO: add legend item indicating "maximum value"

## Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()

作为结果,我得到了: 绘图图片 如何添加适当的图例项?
3个回答

17

如果使用“name”参数创建项,则pyqtgraph会自动将该项添加到图例中。在上述代码中,唯一需要调整的是:

c3 = plt.plot (y=4, pen='y', name="maximum value")

只要您为曲线提供名称,pyqtgraph将自动创建相应的图例项。 但是,在创建曲线之前,务必调用plt.addLegend()


2
在“谢谢”之前调用 plt.addLegend(),谢谢提醒我 :) - Josh.F

8

对于这个例子,您可以创建一个带有正确颜色的空的PlotDataItem,并像这样将其添加到图例中:

style = pg.PlotDataItem(pen='y')
plt.plotItem.legend.addItem(l, "maximum value")

0

我不认为已接受的答案令人满意

也许它在2015年曾经有效,但对于我的版本(pyqtgraph==0.13.3):

c3 = plt.plot(y=4, pen='y', name="maximum value")

抛出一个 TypeError

c3 = plt.addLine(y=4, pen="y", name="maximum value")

并没有对传奇图例做出任何贡献。

我的解决方案:

  1. 你可以使用标签参数。将一些文字放在线附近,这样它不会显示在图例框中,但仍然有用。
c3 = plt.addLine(y=4, pen="y", label="maximum value")

您可以手动添加图例项,但`addLine`会生成一个不符合要求的`InfiniteLine`。不过,您可以通过相对较小的努力进行猴子补丁
import pyqtgraph as pg

plt = pg.plot()
plt.setWindowTitle("pyqtgraph example: Legend")
legend = plt.addLegend()

c1 = plt.plot([1, 3, 2, 4], pen="r", name="red plot")
c2 = plt.plot(
    [2, 1, 4, 3], pen="g", fillLevel=0, fillBrush=(255, 255, 255, 30), name="green plot"
)
c3 = plt.addLine(y=4, pen="y", name="maximum value")
# legend.addItem expect fist argument to have opts dict
c3.opts = {"pen": "y"}
legend.addItem(c3, "test")

pg.exec()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接