Sanimys
Sanimys

Reputation: 111

Swap axis for a linspace plot

I have a function with an histogram, plotted like this :

import matplotlib.pyplot as plt
import numpy as np

lin = np.linspace(min(foo), max(foo), len(foo))
plt.plot(lin, bar)
plt.hist(bar, density=True, bins=100, histtype='stepfilled', alpha=0.2)
plt.show()

Where foo and bar are simple arrays.

Histogram with function

However, I would want to have the whole thing in a vertical way... I could add orientation='horizontal' to the histogram, but it would not change the function (and from what I have seen, there is nothing similar for a plot -> obviously it wouldn't be a function then, but a curve). Otherwise, I could add plt.gca().invert_yaxis() somewhere, but the same problem resides : plot is used for functions, so the swap of it does... well, that :

After inverting the axis

So, the only way I have now is to manually turn the whole original picture by 90 degrees, but then the axis are turned too and will no longer be on the left and bottom (obviously).

So, have you another idea ? Maybe I should try something else than plt.plot ?

EDIT : In the end, I would want something like the image below, but with axes made right. enter image description here

Upvotes: 1

Views: 232

Answers (2)

treskov
treskov

Reputation: 328

I couldn't find any matplotlib method dealing with the issue. You can rotate the curve in a purely mathematical way, i.e. do it through the rotation matrix. In this simple case it is sufficient to just exchange variables x and y but in general it looks like this (let's take a parabola for a clear example):

rotation = lambda angle: np.array([[ np.cos(angle), -np.sin(angle)],
                          [np.sin(angle), np.cos(angle)]])

x = np.linspace(-10,10,1000)
y = -x**2

matrix = np.vstack([x,y]).T

rotated_matrix = matrix @ rotation(np.deg2rad(90))

fig, ax = plt.subplots(1,2)

ax[0].plot(rotated_matrix[:,0], rotated_matrix[:,1])
ax[1].plot(x,y)

enter image description here

rotated_matrix = matrix @ rotation(np.deg2rad(-45))

fig, ax = plt.subplots(1,2)

ax[0].plot(rotated_matrix[:,0], rotated_matrix[:,1])
ax[1].plot(x,y)

enter image description here

Upvotes: 1

Mad Physicist
Mad Physicist

Reputation: 114468

If you have a plot of y vs x, you can swap axes by swapping arrays:

plt.plot(bar, lin)

There's no special feature because it's supported out of the box. As you've discovered, plotting a transposed histogram can be accomplished by passing in

orientation='horizontal'

Upvotes: 1

Related Questions