首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在悬停框中添加垂直线(见图)

在悬停框中添加垂直线(见图)
EN

Stack Overflow用户
提问于 2020-11-26 18:49:34
回答 1查看 194关注 0票数 2

我正在编写一个程序来快速分析电池充电器之类的测试曲线。我想结合悬停框,它捕捉到每条曲线与垂直线,以便于比较。如果我激活这两个代码,它们会发生碰撞,当我移动鼠标时,会出现一条直线,当我停止鼠标时,它会消失,悬停框也不会捕捉到曲线。

hoverbox是从mplcursors库中创建的,而行是为matplotlib中的cursor小部件创建的。

代码语言:javascript
复制
cursor = Cursor(
    ax2, useblit=True, horizOn=False, vertOn=True, color="red", linewidth=0.5
)

代码语言:javascript
复制
mplcursors.cursor(hover=True)

请在此处完成代码:

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

data = np.loadtxt("test.txt")

x = data[:, 0]
y = data[:, 1]
y2 = data[:, 2]
y3 = data[:, 3]

fig = plt.figure(figsize=(13, 5))

ax = fig.add_subplot(111)

ax.plot(x, y, "--", label="Voltage")
ax.plot(x, y2, "-.", label="Current")


ax2 = ax.twinx()
ax2.plot(x, y3, "g:", label="Temperature")
ax2.set_ylabel("Celsius", color=("LightBlue"))
ax2.set_ylim(18, 100)

fig.legend(
    edgecolor=("DarkBlue"),
    facecolor=("LightBlue"),
    loc="upper right",
    bbox_to_anchor=(1, 1),
    bbox_transform=ax.transAxes,
)

ax.set_title("Test Surveillance", color=("Purple"))
ax.set_xlabel("Milliseconds", color=("LightGreen"))
ax.set_ylabel("Volts and Amps", color=("DarkGrey"))


plt.xlim(0)

# cursor = Cursor(
#     ax2, useblit=True, horizOn=False, vertOn=True, color="red", linewidth=0.5
# )
mplcursors.cursor(hover=True)

plt.show()

额外的好处是:在示例中,X值是以秒为单位测量的(我知道它显示为毫秒)。我想在图片中显示1:45:24或x=5.77e+04的任何实例。这个是可能的吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-26 23:25:09

mplcursors允许显式地设置一个函数,该函数将在每次显示注释时被调用。在那里可以更改显示的文本(以及许多其他属性)。此外,还可以绘制额外的元素,如线。当这些元素被附加到sel.extras时,它们将被自动擦除,然后随着光标位置的变化而重新绘制。

使用ax.xaxis.set_major_formatter()时,将为刻度标签和状态栏中的坐标显示设置格式化功能。

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

def hhmmss_formatter(x, pos=None):
    s = floor(x % 60)
    m = floor((x - s) / 60) % 60
    h = floor(x / 3600)
    return f'{h}:{m:02d}' if s == 0 else f'{h}:{m:02d}:{s:02d}'

def show_annotation(sel):
    xi = sel.target[0]
    vertical_line = ax.axvline(xi, color='red', ls=':', lw=1)
    sel.extras.append(vertical_line)
    # print('label:', sel.artist.get_label())
    y1i = np.interp(xi, x, y)
    y2i = np.interp(xi, x, y2)
    y3i = np.interp(xi, x, y3)
    annotation_str = f'Time: {hhmmss_formatter(xi)}\nVoltage: {y1i:.1f}\nCurrent: {y2i:.1f}\nTemperature: {y3i:.1f}'
    sel.annotation.set_text(annotation_str)

x = np.linspace(0, 85000, 500)
y = np.random.randn(len(x)).cumsum() / 5 + 15
y2 = np.random.randn(len(x)).cumsum() / 5 + 30
y3 = np.random.randn(len(x)).cumsum() / 5 + x / 10000 + 25

fig = plt.figure(figsize=(13, 5))

ax = fig.add_subplot(111)

ax.plot(x, y, "--", label="Voltage")
ax.plot(x, y2, "-.", label="Current")

ax2 = ax.twinx()
ax2.plot(x, y3, "g:", label="Temperature")
ax2.set_ylabel("Celsius", color="LightBlue")
ax2.set_ylim(18, 100)

fig.legend(edgecolor=("DarkBlue"), facecolor=("LightBlue"), loc="upper right", bbox_to_anchor=(1, 1),
           bbox_transform=ax.transAxes, )

ax.set_title("Test Surveillance", color="Purple")
ax.set_xlabel("Seconds", color="LightGreen")
ax.set_ylabel("Volts and Amps", color="DarkGrey")

ax.set_xlim(xmin=0)
ax.xaxis.set_major_formatter(plt.FuncFormatter(hhmmss_formatter))  # show x-axis as hh:mm:ss
ax.xaxis.set_major_locator(plt.MultipleLocator(2 * 60 * 60))  # set ticks every two hours

cursor = mplcursors.cursor(hover=True)
cursor.connect('add', show_annotation)
plt.show()

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

https://stackoverflow.com/questions/65020537

复制
相关文章

相似问题

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