Search code examples
pythonnumpymatplotlibscipystep

Matplotlib step plot rotation


I'm trying to rotate correctly the matplotlib step plot. First I swapped the x and y axes and reversed the y axis. I made the step plot again. However, the direction of the step line (blue color) was not as desired in the right picture and the red colored stepping line is the superimposed rotated image of the left picture. Here is my code

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()

I am trying to make red colored step plot as shown in the right picture. How can I do this?

enter image description here


Solution

  • The desired step-style can be obtained by shifting a little bit the second coordinates and using 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)
    

    results