首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python Matplotlib Twinx()游标值

Python Matplotlib Twinx()游标值
EN

Stack Overflow用户
提问于 2016-02-02 01:37:37
回答 1查看 1.4K关注 0票数 1

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

有办法在第二轴和第一y轴之间切换第四条吗?

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

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

代码语言:javascript
复制
    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()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-02 10:20:45

您可以使用出色的答案here同时显示两个坐标。为了得到两点之间的距离,你可以把这个想法和ginput结合起来,从一个映射到另一个,然后把结果添加为标题,

代码语言:javascript
复制
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()

这给出了这样的结果

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

https://stackoverflow.com/questions/35143600

复制
相关文章

相似问题

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