您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在子图中选择一个点并在matplotlib中的相邻子图中将其突出显示(扩展到点的区域)

如何在子图中选择一个点并在matplotlib中的相邻子图中将其突出显示(扩展到点的区域)

您已经在使用当前代码的正确轨道上。基本上,您只是plt.draw()onpick函数中缺少对的调用

但是,在我们的评论讨论中,mpldatacursor出现了,您询问了一个以这种方式做事的例子。

目前HighlightingDataCursormpldatacursor设置围绕突出的整个的思想Line2D的艺术家,它不只是一个特定的索引。(这故意受到限制,因为在matplotlib中没有为任何艺术家绘制任意高光的好方法,因此我将高光部分保持较小。)

但是,您可以将类似于此的子类化(假设您正在使用,plot并且希望使用每个轴上绘制的第一件事)。我还要说明如何使用point_labels,以防每个显示点都有不同的标签

import numpy as np
import matplotlib.pyplot as plt
from mpldatacursor import HighlightingDataCursor, DataCursor

def main():
    fig, axes = plt.subplots(nrows=2, ncols=2)
    for ax, marker in zip(axes.flat, ['o', '^', 's', '*']):
        x, y = np.random.random((2,20))
        ax.plot(x, y, ls='', marker=marker)
    IndexedHighlight(axes.flat, point_labels=[str(i) for i in range(20)])
    plt.show()

class IndexedHighlight(HighlightingDataCursor):
    def __init__(self, axes, **kwargs):
        # Use the first plotted Line2D in each axes
        artists = [ax.lines[0] for ax in axes]

        kwargs['display'] = 'single'
        HighlightingDataCursor.__init__(self, artists, **kwargs)
        self.highlights = [self.create_highlight(artist) for artist in artists]
        plt.setp(self.highlights, visible=False)

    def update(self, event, annotation):
        # Hide all other annotations
        plt.setp(self.highlights, visible=False)

        # Highlight everything with the same index.
        artist, ind = event.artist, event.ind
        for original, highlight in zip(self.artists, self.highlights):
            x, y = original.get_data()
            highlight.set(visible=True, xdata=x[ind], ydata=y[ind])
        DataCursor.update(self, event, annotation)

main()

在此处输入图片说明

同样,这假设您正在使用plot而不是scatter。可以使用进行此操作scatter,但是您需要更改大量令人讨厌的细节。(没有突出显示任意matplotlib艺术家的通用方法,因此您必须有很多非常冗长的代码才能分别处理每种类型的艺术家。)

希望它是有用的,无论如何。

其他 2022/1/1 18:27:21 有727人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶