Home > Software design >  Plot y-axis in python to be independent of y-values
Plot y-axis in python to be independent of y-values

Time:09-09

I am a beginner and I am trying to plot some data in python but fail to do so in a satisfying manner. I have a time-series where my y-variable 'alpha' can take 4 different values: 0.0001, 0.001, 0.01 and 0.1.

When I plot this with the regular approach (see below), my y-axis is falsely scaled: I just want these 4 different values for alpha on my y-axis, plotted with the same distance to each other, I do not want the y-scale to reflect their 'true' distances. Anyone know how to specify that?

Pls find below my code! Thx a lot!:)

import matplotlib.pyplot as plt
import numpy as np

d1 = {'Year': [1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007], 
'Alpha': [0.0001, 0.1, 0.01, 0.1, 0.0001, 0.001, 0.1, 0.0001, 0.01, 0.001, 0.0001, 0.1]}

df = pd.DataFrame(data=d1)

plt.plot('Year', 'Alpha', data=df, label = "Alpha Value")
plt.show()  

CodePudding user response:

How about this?

import matplotlib.pyplot as plt
import numpy as np

d1 = {'Year': [1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007], 
'Alpha': [0.0001, 0.1, 0.01, 0.1, 0.0001, 0.001, 0.1, 0.0001, 0.01, 0.001, 0.0001, 0.1]}

df = pd.DataFrame(data=d1)
Alphas = sorted(df.Alpha.unique().tolist())
new_ticks = np.arange(1,len(Alphas) 1)
modict = dict(zip(Alphas, new_ticks))

df.Alpha = df.Alpha.apply(lambda x: modict[x])

plt.plot('Year', 'Alpha', data=df[['Year','Alpha']])
plt.xlabel('Year')
plt.ylabel('Alpha')
plt.yticks(new_ticks, Alphas)
plt.show()  
  • Related