在matplotlib中同时显示图的注释文本

问题描述 投票:1回答:1

我正在尝试同时显示同一图形(或图)中多个图的注释文本。下面的代码运行完美,但是它一次只显示一个图的注释,但是我的图形有多个图。 plot1_list,plot2_list,plot3_list是我图中的绘图列表。在我的图中,注释文本采用“标签”的形式。如何同时显示每个列表中每个图的注释文本?

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())

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

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)

Attached is the image of a sample plot

python-3.x matplotlib plot annotations label
1个回答
0
投票

根据您的情况,每条曲线都需要一个单独的放大器。这样,它们每个都可以单独打开或关闭。

该代码看起来比必要的要复杂一些。这是一个简化的尝试:

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

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)

plot1a, = host.plot(x, y, c='crimson', ls=':', label='plot 1 a')
plot1b, = host.plot(x, y+10, c='dodgerblue', ls='-', label='plot 1 b')
plot2, = par1.plot(x, y1, c='crimson', ls='--', label='plot 2')
plot3, = par2.plot(x, y2, c='limegreen', label='plot 3')

for i, plot in enumerate([plot1a, plot1b, plot2, plot3]):
    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()
© www.soinside.com 2019 - 2024. All rights reserved.