Nicolás Medina
Nicolás Medina

Reputation: 59

Exchange the x axis for the y axis in python

I have a python code that read several files and returns the next plot:

plot

Now I want to visualize it exchanging the x axis by the y axis. I know that I can do this in matplotlib just putting plt.plot(y,x) instead of plt.plot(x,y), but I have 8 different plots in the figure, so changing everything one by one could be annoying if the number of plots rises: Is there a way to change the axis before show the image?

Here is part of the code:

plt.figure(figsize=(14,8))

plt.plot(Ks_d001,std_d001,'k.',ms=2)#,label='all population')
plt.plot(Ks_d002,std_d002,'k.',ms=2)

KS = np.concatenate([Ks_d001,Ks_d002])
STD = np.concatenate([std_d001,std_d002])

grid = np.linspace(11.5,max(KS),50)
k0 = smooth.NonParamRegression(KS, STD, method=npr_methods.SpatialAverage())
k0.fit()       

plt.plot(grid, k0(grid), label="non-param. fit", color='red', linewidth=2)

plt.plot(Ks_Eta_d001,std_Eta_d001,'s',ms=10,color='green',label='Eta d001')
plt.plot(Ks_Eta_d002,std_Eta_d002,'s',ms=10,color='blue',label='Eta d002')

plt.plot(Ks_IP_d001,std_IP_d001,'p',ms=10,color='cyan',label='IP d001')
plt.plot(Ks_IP_d002,std_IP_d002,'p',ms=10,color='orange',label='IP d002')

plt.plot(Ks_GLS_d001,std_GLS_d001,'h',ms=10,color='red',label='GLS d001')
plt.plot(Ks_GLS_d002,std_GLS_d002,'h',ms=10,color='yellow',label='GLS d002')

Upvotes: 1

Views: 5827

Answers (1)

MSeifert
MSeifert

Reputation: 152587

There is (as far as I know) no function in matplotlib but in general you could just use some data-structure to hold your values which makes it easier to change properties globally or individually:

#         Name             x            y          m
plots = {'Eta d001': [[Ks_Eta_d001, std_Eta_d001, 's'], {'ms': 10, 'color': 'green'}],
         'Eta d002': [[Ks_Eta_d002, std_Eta_d002, 's'], {'ms': 10, 'color': 'blue'}],
         ...}

and then make a plot loop:

for plotname, ((x, y, marker), kwargs) in plots.items():
    plt.plot(x, y, marker, label=plotname, **kwargs)

changing x and y is then as easy as:

for plotname, ((x, y, marker), kwargs) in plots.items():
    plt.plot(y, x, marker, label=plotname, **kwargs)

The dictionary doesn't preserve the original order but when plotting that shouldn't matter much. If it does matter use collections.OrderedDict instead of the normal dict.

Upvotes: 2

Related Questions