简体   繁体   English

如何使用多条曲线添加悬停注释

[英]How to add hovering annotations with multiple curves

I am using matplotlib to plot multiple curves (time series) in one plot.我正在使用 matplotlib 在一个图中绘制多条曲线(时间序列)。 To do this, I use a for loop as seen below.为此,我使用了如下所示的for循环。

%matplotlib

for i in range(0, len(force)):

    plt.plot(distance, (force[i]), alpha=0.1)
    
    plt.xlabel('Distance [mm]', fontsize=12)
    plt.ylabel('Force [N]', fontsize=12)

Unfortunately, with the number of curves (approx. 70) that I have, the plot would be unreadable if I labeled each curve.不幸的是,由于我拥有的曲线数量(大约 70 条),如果我标记每条曲线,则该图将无法阅读。 Does anyone know of a way to create labels that only appear when the cursor hovers in the vicinity of that curve (timeseries)?有谁知道创建仅当光标悬停在该曲线附近(时间序列)时才出现的标签的方法?

I looked on the example from this post, but have no clue how to adapt it to my issue:我查看了这篇文章中的示例,但不知道如何使其适应我的问题:

Possible to make labels appear when hovering over a point in matplotlib? 将鼠标悬停在 matplotlib 中的某个点上时可以显示标签吗?

You could use mplcursors .你可以使用mplcursors Each curve can have a unique label, which is shown by default.每条曲线都可以有一个唯一的标签,默认情况下会显示。

from matplotlib import pyplot as plt
import mplcursors
import numpy as np

force = np.random.randn(70, 100).cumsum(axis=1)
force -= force.mean(axis=1, keepdims=True)
plt.figure(figsize=(12, 5))
for i in range(len(force)):
     plt.plot(force[i], alpha=0.2, label=f'force[{i}]')
plt.margins(x=0.01)
cursor = mplcursors.cursor(hover=True)
plt.show()

显示 70 条标记曲线的 mplcursors

If you're working with a Jupyter notebook, you might need %matplotlib nbagg or %matplotlib qt instead of %matplotlib inline to enable interactivity.如果您正在使用 Jupyter 笔记本,您可能需要%matplotlib nbagg%matplotlib qt而不是%matplotlib inline来启用交互性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM