首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在matplotlib中同时显示绘图的注解文本

在matplotlib中同时显示绘图的注解文本
EN

Stack Overflow用户
提问于 2020-02-13 21:36:13
回答 1查看 351关注 0票数 1

我正试图在同一图形(或图形)中同时显示多个绘图的注释文本。下面的代码工作得很好,但它一次只为一个绘图显示一个注释,但我的图形有多个绘图。plot1_list、plot2_list、plot3_list是我的图表中的绘图列表。在我的绘图中,注释文本以"labels“的形式出现。如何在每个列表中同时显示每个绘图的注释文本?

代码语言:javascript
复制
import mplcursors



cursor1 = mplcursors.cursor(plot1_list, hover=False, bindings={"toggle_visible": "h", "toggle_enabled": "e"})
@cursor1.connect("add")
def on_add(sel):
    sel.annotation.set_text(sel.artist.get_label())

cursor2 = mplcursors.cursor(plot2_list, hover=False, bindings={"toggle_visible": "h", "toggle_enabled": "e"})
@cursor2.connect("add")
def on_add(sel):
    sel.annotation.set_text(sel.artist.get_label())

cursor3 = mplcursors.cursor(plot3_list, hover=False, bindings={"toggle_visible": "h", "toggle_enabled": "e"})
@cursor3.connect("add")
def on_add(sel):
    sel.annotation.set_text(sel.artist.get_label())

上述代码中的绘图列表是使用以下代码创建的:

代码语言:javascript
复制
label1 = str("MAXIMUM HEAD=" + str(m_head))
label2 = str("MAXIMUM POWER=" + str(m_power))
label3 = str("MAXIMUM EFFICIENCY=" + str(m_efficiency))

plot1, = host.plot(y0, y, linestyle=styles[0], color=colorstouse[count], label=label1)
plot2, = par1.plot(y0, y1, linestyle=styles[1], color=colorstouse[count], label=label2)
plot3, = par2.plot(y0, y2, linestyle=styles[2], color=colorstouse[count], label=label3)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-13 23:41:49

在您的示例中,每条曲线都需要一个单独的mplcursor。这样,它们中的每一个都可以单独打开或关闭。

代码看起来比必要的要复杂一点。这里是一个简化的尝试。该示例显示了使用3个轴的15条曲线。请注意,它可能会变得非常拥挤,因此90个曲线可能会有点太多。

代码语言:javascript
复制
from matplotlib import pyplot as plt
import numpy as np
import mplcursors

num_devices = 5
fig, host = plt.subplots(figsize=(12, 4))
fig.subplots_adjust(right=0.8)

par1 = host.twinx()
par2 = host.twinx()
par2.spines["right"].set_position(("axes", 1.1))

x = np.linspace(0, 10)
y = -x ** 2 + 5 * x + 10
y1 = 10 + 20 * np.cos(x)
y2 = 30 + 5 * np.sin(x)

ys = [y + np.random.uniform(10, 30) for i in range(num_devices)]
y1s = [y1 + np.random.uniform(10, 30) for i in range(num_devices)]
y2s = [y2 + np.random.uniform(10, 30) for i in range(num_devices)]

colors = plt.cm.tab10.colors
plots = []
for dev in range(num_devices):
    plot1 = host.plot(x, ys[dev], c=colors[dev], ls='-', label=f'plot 1 - dev {dev}')
    plot2, = par1.plot(x, y1s[dev], c=colors[dev], ls='--', label=f'plot 2 - dev {dev}')
    plot3, = par2.plot(x, y2s[dev], c=colors[dev], ls=':', label=f'plot 3 - dev {dev}')
    plots += [plot1, plot2, plot3]

print(plots)
for i, plot in enumerate(plots):
    cursor = mplcursors.cursor(plot, hover=False, bindings={"toggle_visible": "h", "toggle_enabled": "e"})
    cursor.connect("add", lambda sel: sel.annotation.set_text(sel.artist.get_label()))
plt.show()

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60209132

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档