如何在matplotlib中突出显示行集合 [英] how to highlight line collection in matplotlib

查看:56
本文介绍了如何在matplotlib中突出显示行集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 mpldatacursor 模块( https://stackoverflow.com/users/325565/joe-kington )突出显示matplotlib中的行.我在 https://github.com/joferkington/mpldatacursor 找到了突出显示行的示例.在示例中,线条是一条一条绘制的.在下面的代码中,我想使用 line collection 绘制线条,因为要绘制的线条太多了.

I am trying to use mpldatacursor module (https://stackoverflow.com/users/325565/joe-kington) to highlight lines in matplotlib. I found examples to highlight lines at https://github.com/joferkington/mpldatacursor. In the example the lines were plotted one-by-one. In my code below, I want to plot the lines using line collection because there are so many lines to plot.

但是当我运行代码并单击一行时,它并没有突出显示它.请纠正我做错的地方,非常感谢.

But when I run the code and I click on a line, it does not highlight it. Please, correct what I am doing wrong, many thanks.

import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
import mpldatacursor

if __name__ == '__main__':
fig, ax = plt.subplots()        
xlist = [[(0.21, 0.50), (0.42, 0.80)], [(0.13, 0.62), (0.46, 0.77), (0.81, 0.90)], [(0.32, 0.12), (0.64, 0.80)], [(0.54, 0.20), (0.87, 0.80)]]

lineCollection = LineCollection(xlist)
lines = ax.lines
mpldatacursor.HighlightingDataCursor(lines)
ax.add_collection(lineCollection)

plt.show()

推荐答案

您可以在pick_event处理程序中获取行的索引,并更改颜色:

You can get the index of line in pick_event handler, and change the color:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

fig, ax = plt.subplots()        
xlist = [[(0.21, 0.50), (0.42, 0.80)], [(0.13, 0.62), (0.46, 0.77), (0.81, 0.90)],
         [(0.32, 0.12), (0.64, 0.80)], [(0.54, 0.20), (0.87, 0.80)]]

normal_selected_color = np.array([[0, 0, 1, 1.0], [1, 0, 0, 1.0]])
selected = np.zeros(len(xlist), dtype=int)
colors = normal_selected_color[selected]
lines = LineCollection(xlist, pickradius=10, colors=colors)
lines.set_picker(True)

ax.add_collection(lines)

def on_pick(evt):
    if evt.artist is lines:
        ind = evt.ind[0]
        selected[ind] = 1 - selected[ind]
        lines.set_color(normal_selected_color[selected])
        fig.canvas.draw_idle()


fig.canvas.mpl_connect("pick_event", on_pick)
plt.show()

只选择一行:

def on_pick(evt):
    if evt.artist is lines:
        ind = evt.ind[0]
        selected[:] = 0
        selected[ind] = 1
        lines.set_color(normal_selected_color[selected])
        fig.canvas.draw_idle()

这篇关于如何在matplotlib中突出显示行集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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