【问题标题】:How to print labels of individual bars of barchart on clicking them in Python如何在Python中单击条形图的各个条形图时打印它们的标签
【发布时间】:2019-11-06 22:23:34
【问题描述】:

点击条形时我无法打印标签

我已经尝试使用 get_label() 方法,但标签没有打印在点击栏上

import matplotlib.pyplot as plt
import numpy as np

def main():
    fig = plt.figure()
    ax = fig.add_subplot(111)
    labels = ['Apple', 'Mango', 'Orange']
    size=[20, 40, 60]
    y_pos=np.arange(len(labels))    
    wedges = ax.bar(y_pos,size)
    plt.xticks(y_pos,labels)
    plt.xlabel("Fruits")
    plt.ylabel("Count")    
    plt.title("Fruits Count")
    make_picker(fig,wedges)
    plt.show()

def make_picker(fig, wedges):
    def onclick(event):
        wedge= event.artist
        label = wedge.get_label()
        print(label)
    for wedge in wedges:
        wedge.set_picker(True)
    fig.canvas.mpl_connect('pick_event', onclick)

if __name__ == '__main__':
    main()

预期结果:当我单击任何条时,应打印该条的相应标签。获得的结果:当我点击栏时,nolegend 正在打印

【问题讨论】:

    标签: python matplotlib onclick label bar-chart


    【解决方案1】:

    如果你想使用Artist.get_label(),那么你需要在somewhere设置艺术家的标签,使用Artist.set_label(label):

    def main():
        fig = plt.figure()
        ax = fig.add_subplot(111)
        labels = ['Apple', 'Mango', 'Orange']
        size=[20, 40, 60]
        y_pos=np.arange(len(labels))
        wedges = ax.bar(y_pos,size)
        # Assign a label to each of the artist to be retrieved later
        for w,l in zip(wedges, labels):
            w.set_label(l)
        plt.xticks(y_pos,labels)
        plt.xlabel("Fruits")
        plt.ylabel("Count")
        plt.title("Fruits Count")
        make_picker(fig,wedges)
        plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-03
      相关资源
      最近更新 更多