【问题标题】:Plot secondary data as ticks on a second y axis将辅助数据绘制为第二个 y 轴上的刻度
【发布时间】:2017-04-24 06:57:46
【问题描述】:

我想绘制辅助数据,而不是作为绘图,而是作为 y 轴。 我试图在图中说清楚。 首先,我绘制了 A 与 C。

现在我想绘制 A 与 B,但不是一条线,而是与 A 重合的数字。 在这种情况下,A 是深度。深入有两个测量值 B 和 C。我已经将 A 和 C 之间的关系绘制为线图。现在我想将 A 和 B 的关系作为一种表格添加到辅助 y 轴中。 注意:我不需要辅助 y 轴!我需要将 B(A=2)、B(A=0)、B(A=-2) 等的值记为第二个 y 轴上的数字。所以只有 A 的刻度必须在第二个轴上得到一个数字 B(A)。

          0 -              +   - 0
         -1 -             +    - 0.5
         -2 -            +     - 0.62
         -3 -           +      - 2.1
       A -4 -          +       - 1.5  B
         -5 -       +++        - 1.9
         -6 -     +            - 2.8
         -7 -  +               - 3.0
         -8 - +                - 4.1
            --------------------
                       C

[示例][1]

我已经实现了 Stefan 的示例,但使用列表而不是函数。 (dpt[0]=a[0]=c[0]dpt[22]=a[22]=c[22]等) 我的清单很长,有很多小数。因此,我的刻度值与列表中的数据不完全对应。我找到了最接近的值并将数字四舍五入。对于那些感兴趣的人,这对我有用:

    ax2 = ax1.twinx() 
    depth = [round(x, 1) for x in dpt]  # In my case the original list used 5 decimals and next line ‘difr’ has 1 decimal.
    def mapAtoB(A):
        difr= min(depth, key=lambda x: abs(x - A))   #Find the value in ‘depth’ which is closest to the tick-value A.
        B = round(a[depth.index(difr)],2)            #The index value (difr==depth) is plugged into the list I want on the y-axis. The obtained value needed to be rounded as well. 
        return B

    ax2.plot(c, dpt, alpha=0)
    ticks = ticker.FuncFormatter(lambda dpt, pos: '{0:g}'.format(mapAtoB(dpt)))
    ax2.yaxis.set_major_formatter(ticks)

我希望我的例子足够清楚!

【问题讨论】:

  • 我怎样才能用 A = [1, 2, 3, ...], B= [2, 4, 8, 16,..) 和 C= [3, 9 , 27, 81, ....]。所有相同的长度和 A(0) 对应于 B(0) 和 C(0)。 A(22) 对应于 B(22) 和 C(22) 等?

标签: python matplotlib plot


【解决方案1】:

您大概知道A 如何映射到B,只需将 y 刻度从 A 转换为 B 的 y 刻度,绘制两者并隐藏 B 的绘图。

例子:

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np

def mapAtoB(A):
    B = A**2
    return B

x = [1,2,3,4,5]

y = np.power(x,2)


fig, ax1 = plt.subplots()
ax1.grid()
ax1.plot(x,y, marker = 'X')
ax1.set_xlabel('x-axis')
ax1.set_yticks(y)

ax2 = ax1.twinx()
ax2.plot(x, y, alpha=0)
ax2.set_yticks(y)
ticks = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(mapAtoB(x)))
ax2.yaxis.set_major_formatter(ticks)

plt.show()

【讨论】:

    猜你喜欢
    • 2021-11-07
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    • 2019-05-28
    • 1970-01-01
    相关资源
    最近更新 更多