【发布时间】: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)
下一个代码用于绘制堆叠条形图,但不显示标签。虽然没有返回错误信息,但无法获取标签并显示。
# 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