【问题标题】:Matplotlib step plot rotationMatplotlib 阶梯图旋转
【发布时间】:2021-10-11 09:48:18
【问题描述】:

我正在尝试正确旋转 matplotlib 步进图。首先,我交换了 x 和 y 轴并反转了 y 轴。我再次制作了阶梯图。但是,右图中的阶梯线(蓝色)的方向并不理想,红色的阶梯线是左图的叠加旋转图像。这是我的代码

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(14)
y = np.sin(x / 2)

fig, (ax, bx) = plt.subplots(nrows=1, ncols=2, figsize=(11.5, 5.5))
fig.subplots_adjust(left=0.08, bottom=0.13, top=0.98, right=0.97, wspace=0.2, hspace=0.0)

ax.step(x, y, where='mid', c='r')
ax.plot(x, y, 'o--', color='grey', alpha=0.3)

bx.invert_yaxis()
bx.step(y, x, where='pre', c='b')
bx.plot(y, x, 'o--', color='grey', alpha=0.3)

plt.show()

我正在尝试制作红色阶梯图,如右图所示。我该怎么做?

【问题讨论】:

    标签: python numpy matplotlib scipy step


    【解决方案1】:

    可以通过移动第二个坐标并使用where=pre来获得所需的步进样式。

    def plot_step_invert_mid(x, y, *args, **kwargs):
        y_new = np.insert(y, 0, y[0])
        y_new = 0.5 * (y_new[1:] + y_new[:-1])
        x_new = np.append(x, x[-1])
        y_new = np.append(y_new, y[-1])
        plt.step(x_new, y_new, where="pre", *args, **kwargs)
    
    fig, (ax, bx) = plt.subplots(nrows=1, ncols=2, figsize=(11.5, 5.5))
    fig.subplots_adjust(left=0.08, bottom=0.13, top=0.98, right=0.97, wspace=0.2, hspace=0.0)
    
    ax.step(x, y, where="mid", c='r')
    ax.plot(x, y, 'o--', color='grey', alpha=0.3)
    
    bx.invert_yaxis()
    plot_step_invert_mid(y, x)
    bx.plot(y, x, 'o--', color='grey', alpha=0.3)
    

    【讨论】:

    • 不错的答案,我认为让数据完好无损。
    • 一个小缺点在于plot_step_invert_mid(y, x, "ro-") 不会在所需位置显示标记。
    • 啊,对,我明白你的意思了……这是一个棘手的问题。当然,您始终可以绘制数据本身。这将对 matplotlib 进行很好的增强。
    • 不使用外部包是很好的答案。非常感谢您定义子程序。
    • 再次感谢@noin,应该对阶梯图的“pre”和“post”选项进行哪些更改?
    【解决方案2】:

    我建议您使用scipy.interpolate.interp1d 插入原始曲线,而不是使用matplotlib.pyplot.step 绘图方法。这是因为interp1d 生成了一个新向量,您可以随意操作。
    在下面的代码中:

    1. xy 是原始曲线向量(长度为 14)
    2. xxyy是原始曲线插值向量(长度N

    为了旋转绘图,您可以简单地将xyxxyyplt.plot 中交换:

    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.interpolate import interp1d
    
    x = np.arange(14)
    y = np.sin(x/2)
    
    N = 1000
    xx = np.linspace(0, 13, N)
    yy = interp1d(x, y, kind = 'nearest')(xx)
    
    fig, (ax, bx) = plt.subplots(nrows = 1, ncols = 2, figsize = (11.5, 5.5))
    fig.subplots_adjust(left = 0.08, bottom = 0.13, top = 0.98, right = 0.97, wspace = 0.2, hspace = 0.0)
    
    ax.plot(xx, yy, 'r')
    ax.plot(x, y, 'o--', color = 'grey', alpha = 0.3)
    
    bx.invert_yaxis()
    bx.plot(yy, xx, 'r')
    bx.plot(y, x, 'o--', color = 'grey', alpha = 0.3)
    
    plt.show()
    

    【讨论】:

    • 我发现这个答案的原始版本更有趣,因为它将问题概括为任何角度。
    • 谢谢,我觉得你是对的,但是原版中y轴没有反转,所以回答没有解决提问者的具体问题;后来才注意到
    • 这是一个非常有趣的解决方案,但不希望使用外部子程序,至少对我来说是这样。
    猜你喜欢
    • 2018-10-17
    • 1970-01-01
    • 2012-07-03
    • 2013-10-10
    • 2012-12-18
    • 1970-01-01
    • 2019-11-22
    • 2014-12-04
    • 2016-05-06
    相关资源
    最近更新 更多