【问题标题】:Click event with a Matplotlib bar chart带有 Matplotlib 条形图的单击事件
【发布时间】:2019-06-10 15:10:40
【问题描述】:

我正在使用 Matplotlib 制作堆积条形图,并希望显示点击数据的标签。

我编写了一个代码来显示简单折线图的标签。当我尝试对条形图执行相同操作时,它不起作用。下面是使用折线图的代码。

import numpy as np
import matplotlib.pyplot as plt

# plots port counts per address as a stacked bar graph
fig=plt.figure()
ax=fig.add_subplot(111)
text=ax.text(0,0, '', va='baseline', ha='left')

# plot 
y=np.array([[1,2,3],[4,5,6]])

for i in range(2):
    ax.plot(y[i, :], gid=i)

def on_click(event):
    for curve in ax.get_lines():
        if curve.contains(event)[0]: gid=curve.get_gid()
    text.set_text('Class %s' % gid)

fig.canvas.mpl_connect('button_press_event', on_click)

当我点击一条线时,它的标签(gid)如下图所示。

下一个代码用于绘制堆叠条形图,但不显示标签。虽然没有返回错误信息,但无法获取标签并显示。

# plots port counts per address as a stacked bar graph
fig=plt.figure()
ax=fig.add_subplot(111)
text=ax.text(0,0, '', va='baseline', ha='left')
bottom=np.array([0,0,0])

# plot 
x_pos=np.arange(3)
y=np.array([[1,2,3],[1,3,5]])

for i in range(2):
    ax.bar(x_pos, y[i, :], align='center', bottom=bottom, alpha=0.5, gid=i)

    # update the bar bases for the next iteration
    bottom=np.add(bottom,y[i, :] )

def on_click(event):
    gid='-'
    for curve in ax.get_lines():
        gid='TEST'
        if curve.contains(event)[0]: 
            gid=curve.get_gid()
    text.set_text('Class %s' % gid)

fig.canvas.mpl_connect('button_press_event', on_click)

我假设ax.bar 不会创建要由get_lines 重新调整的行,因此它以0 次迭代退出for curve in ax.get_lines() 循环,因为单击图表时如何设置文本,如下图所示.

我想知道如何通过单击堆积条形图来显示标签。

【问题讨论】:

    标签: python matplotlib plot onclick


    【解决方案1】:

    找出鼠标事件包含在哪个艺术家中的概念在使用悬停时很有用,例如How to annotate the values of X and Y while hovering mouse over the bar graph

    相比之下,这里要点击条形。这是通过“选择器”完成的;实际上,在这种情况下,线条或条形之间没有区别。

    所以以下两种情况都适用。单击第一个条时显示“Class bar: 0”,第一行显示“Class line: 0”。

    import numpy as np
    import matplotlib.pyplot as plt
    
    # plots port counts per address as a stacked bar graph
    fig=plt.figure()
    ax=fig.add_subplot(111)
    text=ax.text(0,0, '', va='baseline', ha='left')
    bottom=np.array([0,0,0])
    
    # plot 
    x_pos=np.arange(3)
    y=np.array([[1,2,3],[1,3,5]])
    
    for i in range(2):
        ax.bar(x_pos, y[i, :], align='center', bottom=bottom, alpha=0.5, gid=f"bar: {i}", picker=4)
        ax.plot(y[i, :], gid=f"line: {i}", picker=4)
        # update the bar bases for the next iteration
        bottom=np.add(bottom,y[i, :] )
    
    def on_click(event):
        text.set_text(f"Class {event.artist.get_gid()}")
        fig.canvas.draw_idle()
    
    fig.canvas.mpl_connect('pick_event', on_click)
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-04
      • 2011-08-19
      • 2019-06-05
      • 1970-01-01
      • 2017-05-13
      • 2020-02-13
      相关资源
      最近更新 更多