Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib swap x and y axis

Hello I have made a plot in matplot lib using pandas however I need to swap my x and y axis.

Here is my plot:

broomstick plot
broomstick plot

however i need it to look like this:

correct broomstick plot
correct broomstick plot

I'm using a pandas dataframe to plot the data.

I've looked over some documentation and other posts regarding swapping the x and y axis and haven't found any easy way to do this. Here some of my python code:

python code
python code

Any resources or ideas would be greatly appreciated.

like image 280
Cameron Olson Avatar asked Aug 16 '26 09:08

Cameron Olson


1 Answers

Try this. You need to include your y_vals as an additional column. So with this you can just specify your axis here df.plot(x=, y=):

Code:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt


x = np.linspace(0, 10, 100)
y = np.cos(x)

df = pd.DataFrame({'y': y, 'x': x})

df.plot(x='x')
plt.show()

df.plot(x='y')
plt.show()

Plots:

enter image description here enter image description here

like image 177
trsvchn Avatar answered Aug 17 '26 22:08

trsvchn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!