Matplotlib 步骤图旋转

Matplotlib step plot rotation

我正在尝试正确旋转 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()

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

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

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

为了旋转情节,您可以简单地将 xyxxyy 交换 plt.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()

可以通过稍微移动第二个坐标并使用 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)