Python Matplotlib Twinx() 光标值

标签 python python-2.7 matplotlib scipy

我想使用光标(x,y 值显示在图的左下角)来测量两点之间的 y 和 x 距离,但这仅适用于第二个轴上绘制的数据。

有没有办法在第二个轴和第一个 y 轴之间来回切换?

请注意:我不需要以编程方式获取点之间的距离,只是在查看图中的数据时使用光标。

不确定这是否有帮助,但我的代码实际上是从 matplotlib 页面绘制两个轴的示例:

    fig, ax1 = plt.subplots()
    ax1.plot(sensor1, 'b-')
    ax1.set_xlabel('(time)')
    # Make the y-axis label and tick labels match the line color.
    ax1.set_ylabel('Sensor 1', color='b')
    for tl in ax1.get_yticklabels():
        tl.set_color('b')


    ax2 = ax1.twinx()
    ax2.plot(sensor2, 'r.')
    ax2.set_ylabel('Sensor 2', color='r')
    for tl in ax2.get_yticklabels():
        tl.set_color('r')
    plt.show()

最佳答案

您可以使用优秀的答案here同时显示两个坐标。为了获得两点之间的距离,您可以将此想法与 ginput 结合起来,从一个点映射到另一个点,并将结果添加为标题,

import matplotlib.pyplot as plt
import numpy as np

#Provide other axis
def get_othercoords(x,y,current,other):

    display_coord = current.transData.transform((x,y))
    inv = other.transData.inverted()
    ax_coord = inv.transform(display_coord)
    return ax_coord

#Plot the data
fig, ax1 = plt.subplots()
t = np.linspace(0,2*np.pi,100)
ax1.plot(t, np.sin(t),'b-')
ax1.set_xlabel('(time)')
ax1.set_ylabel('Sensor 1', color='b')
for tl in ax1.get_yticklabels():
    tl.set_color('b')

ax2 = ax1.twinx()
ax2.plot(t,3.*np.cos(t),'r-')
ax2.set_ylabel('Sensor 2', color='r')
for tl in ax2.get_yticklabels():
    tl.set_color('r')

#Get user input
out = plt.ginput(2)

#2nd axis from input
x2b, x2t = out[0][0], out[1][0]
y2b, y2t = out[0][1], out[1][1]

#Draw line
ax2.plot([x2b, x2t],[y2b, y2t],'k-',lw=3)

#1st axis from transform
x1b, y1b = get_othercoords(x2b,y2b,ax2,ax1)
x1t, y1t = get_othercoords(x2t,y2t,ax2,ax1)
plt.title("Distance x1 = " + str(x1t-x1b) + " y1 = " + str(y1t-y1b) + "\n"
          "Distance x2 = " + str(x2t-x2b) + " y2 = " + str(y2t-y2b))
plt.draw()
plt.show()

这给出了类似的东西,

enter image description here

关于Python Matplotlib Twinx() 光标值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35143600/

相关文章:

python - pandas 将 asof 与多个匹配项合并

python - 为什么这个 Python 脚本会删除 '.txt' 文件,以及所有 '.tmp' 文件?

Python-生成特定自相关的数组

mongodb - Redis:设置时间=获取时间。为什么?

python - Python 中的实时 FFT 绘图 (MatPlotLib)

python - MySQL连接器无法正常工作并给出错误

Python 2.7.5 正确的循环语法,正确使用 'while'

python-2.7 - 如何在 Robot Framework 中获取当前日期?

python-3.x - 使用 np.polyfit 沿多项式回归生成的曲线计算和绘制切线

python - 使用 matplotlib 中的 pcolor 时出错