matplotlib堆叠面积图中的动态标签 [英] Dynamic labels in matplotlib stacked area chart

查看:33
本文介绍了matplotlib堆叠面积图中的动态标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理由熊猫创建的堆叠区域图.屏幕截图显示了一个这样的典型图(故意不显示标签):产生该图的相关代码是

  fig,axes = plt.subplots(nrows = 2,ncols = 1)coredata = nonzero.loc[:, nonzero.columns != 'Busy'].plot.area(figsize=(9, 8), ax=axes[0], colormap='jet')

其中 nonzero 是一个较大的数据框.问题是有太多列导致拥挤的图例.与其将图例移出图片,我不希望使用matplotlib的事件来告诉我我将鼠标悬停在图表的哪个元素上.

  def on_move(事件):如果 event.inaxes == 核心数据:# 请帮助fig.canvas.mpl_connect("motion_notify_event",on_move)

该事件完全按照期望触发,但是我在提取悬停的区域(分别是其标签)时遇到困难.coredata.artists 是空的,coredata.lines 是一个 matplotlib.lines.Line2D 元素(据说太低级了).如何访问光标下方的当前区域以显示其标签?

以下是一个最小的例子:

从熊猫

 导入DataFrame,系列从 matplotlib 导入 pyplot 作为 plt#模拟数据d = {'one':Series([1.,2.,3.],index = ['a','b','c']),'二' : 系列([1., 2., 3., 4.], index=['a', 'b', 'c', 'd']),'三':系列([0.5, 0.2, 0.3, 0.1], index=['a', 'b', 'c', 'd']),'四':系列([3., 2., 1., 0.3], index=['a', 'b', 'c', 'd']),}df = 数据帧(d)图,轴 = plt.subplots()图表= df.plot.area(ax = axes)#创建并最初隐藏注释annot = axes.annotate(",xy =(0,0),xytext =(-20,20),textcoords ="offset points",bbox = dict(boxstyle ="round",fc ="w"))annot.set_visible(False)def on_move(事件):如果event.inaxes ==图表:通过#help plz:如何最好地检查我当前将鼠标悬停在一个,两个,三个或四个上?打印(事件.xdata,事件.ydata)fig.canvas.mpl_connect("motion_notify_event",on_move)plt.show()

解决方案

就像悬停散点图一样,参见例如

I'm working with a stacked area plot created by pandas. The screenshots shows one such typical plot (labels are deliberatly not shown): The relevant code producing this plot is

fig, axes = plt.subplots(nrows=2, ncols=1)
coredata = nonzero.loc[:, nonzero.columns != 'Busy'].plot.area(figsize=(9, 8), ax=axes[0], colormap='jet')

where nonzero is a larger dataframe. The issue is that there are too many columns leading to a crowded legend. Instead of moving the legend out of the picture I'd like to use matplotlib's events to tell me which element of the chart I'm hovering over.

def on_move(event):
    if event.inaxes == coredata:
        # help please

fig.canvas.mpl_connect("motion_notify_event", on_move)

The event fires exactly as desired but I have trouble extracting the area I'm hovering over (respectively its label). coredata.artists is empty, coredata.lines is a matplotlib.lines.Line2D element (supposedly too low level). How can I access the current area under the cursor in order to display its label?

Edit: following is a minimal example:

from pandas import DataFrame, Series
from matplotlib import pyplot as plt

# mock data
d = {'one' : Series([1., 2., 3.], index=['a', 'b', 'c']),
     'two' : Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd']),
     'three': Series([0.5, 0.2, 0.3, 0.1], index=['a', 'b', 'c', 'd']),
     'four': Series([3., 2., 1., 0.3], index=['a', 'b', 'c', 'd']),
}
df = DataFrame(d)

fig, axes = plt.subplots()
chart = df.plot.area(ax=axes)

# create and initially hide annotation
annot = axes.annotate("", xy=(0,0), xytext=(-20,20),textcoords="offset points",
                    bbox=dict(boxstyle="round", fc="w"))
annot.set_visible(False)
def on_move(event):
    if event.inaxes == chart:
        pass # help plz: how do I best check I currently hover over one, two, three or four?
        print(event.xdata, event.ydata)
fig.canvas.mpl_connect("motion_notify_event", on_move)

plt.show()

解决方案

Just as when hovering a scatter, see e.g. here or here you need to check if any of the collections contains the mouseevent. To this end you would look over the collections of interest, do the check and if successful may add an identifier to a list.

which = []
for i,c in enumerate(axes.collections):
    if c.contains(event)[0]:
        which.append(i)

You may then use this list to draw a new legend with only the collections identified in that list. Since redrawing the canvas is expensive and may slow down the application one would try to do it as seldom as possible. While moving the mouse, the exact same result would be expected a lot of times, so we may store it and only create a new legend in case it needs to be changed.

from pandas import DataFrame, Series
from matplotlib import pyplot as plt

# mock data
d = {'one' : Series([1., 2., 3.], index=['a', 'b', 'c']),
     'two' : Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd']),
     'three': Series([0.5, 0.2, 0.3, 0.1], index=['a', 'b', 'c', 'd']),
     'four': Series([3., 2., 1., 0.3], index=['a', 'b', 'c', 'd']),
}
df = DataFrame(d)

fig, axes = plt.subplots()
df.plot.area(ax=axes, legend=False)

# create and initially hide annotation
annot = axes.annotate("", xy=(0,0), xytext=(-20,20),textcoords="offset points",
                    bbox=dict(boxstyle="round", fc="w"))
annot.set_visible(False)

last = [None]
def on_move(event):
    if event.inaxes == axes:
        which = []
        for i,c in enumerate(axes.collections):
            if c.contains(event)[0]:
                which.append(i)
        if which != last[0]:
            last[0] = which
            axes.legend([axes.collections[i] for i in which],
                        [df.columns[i] for i in which])
            fig.canvas.draw_idle()

fig.canvas.mpl_connect("motion_notify_event", on_move)

plt.show()

这篇关于matplotlib堆叠面积图中的动态标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆