【问题标题】:How to get the label on bar plot/stacked bar plot in matplotlib?如何在 matplotlib 中获取条形图/堆积条形图上的标签?
【发布时间】:2023-04-01 14:37:01
【问题描述】:

我在 PyQt Canvas 中嵌入了一个非常简单的堆叠 matplotlib 条形图。我正在尝试根据点击获取条形区域(矩形)的相应标签。但是当我尝试打印来自事件的信息时,我总是会得到 _nolegend_。理想情况下,我希望在代码中附加的栏上看到相应的标签。

例如,当您单击 灰色 栏时,它应该打印 a2

import sys
import matplotlib.pyplot as plt

from PyQt4 import QtGui
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas


def on_pick(event):
    print event.artist.get_label()

def main():

    app = QtGui.QApplication(sys.argv)

    w = QtGui.QWidget()
    w.resize(640, 480)
    w.setWindowTitle('Pick Test')

    fig = Figure((10.0, 5.0), dpi=100)
    canvas = FigureCanvas(fig)
    canvas.setParent(w)

    axes = fig.add_subplot(111)

    # bind the pick event for canvas
    fig.canvas.mpl_connect('pick_event', on_pick)

    p1 = axes.bar(1,6,picker=2,label='a1')
    p2 = axes.bar(1,2, bottom=6,color='gray',picker=1,label='a2')

    axes.set_ylim(0,10)
    axes.set_xlim(0,5)

    w.show()

    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

【问题讨论】:

    标签: python matplotlib plot pyqt bar-chart


    【解决方案1】:

    这有点棘手,因为bar 是一个真正由多个组件组成的复杂绘图对象。

    您可以使用get_legend_handles_labels 获取轴的所有艺术家和标签。然后你可以看看你当前的艺术家属于哪个组。

    所以你的回调可能看起来像这样。

    def on_pick(event)
        rect = event.artist
    
        # Get the artists and the labels
        handles,labels = rect.axes.get_legend_handles_labels()
    
        # Search for your current artist within all plot groups
        label = [label for h,label in zip(handles, labels) if rect in h.get_children()]
    
        # Should only be one entry but just double check
        if len(label) == 1:
            label = label[0]
        else:
            label = None
    
        print label
    

    【讨论】:

    • 感谢@Suever,这很有效。你是对的,与通过获取 event.artist.get_label() 的值直接工作的堆叠区域图相比,它非常复杂
    猜你喜欢
    • 2018-01-17
    • 2019-11-28
    • 2021-02-06
    • 2021-02-27
    • 2013-12-22
    • 2017-02-26
    • 2012-12-24
    • 2017-09-19
    • 1970-01-01
    相关资源
    最近更新 更多