Skip to content
Advertisement

Matplotlib flattens the first of two plots when I add the second plot?

Matplotlib madness…

dfin = pd.read_csv(inputfilename, sep=";", encoding='ISO-8859-1')

# create a return column
dfin['return'] = dfin['close'].shift(9) / dfin['close'].shift(12)
# create a cumulative sum column
dfin['return_cum'] = dfin['return'].cumsum()


close = dfin.iloc[:-1]['close']
test = dfin.iloc[:-1]['close'] * dfin.iloc[:-1]['return']


fig, axs = plt.subplots(figsize=(20, 10), sharex=True, sharey=True)
axs.plot(close, color='black')
axs.plot(test, color='blue')
plt.show()
plt.close()

The expected plot

However, when I try to run a cumulative plot of any kind, MPL flattens the first plot and plots the second relative to it:

test = dfin.iloc[:-1]['close'] * dfin.iloc[:-1]['return_cum']

Undesirable type of plot

I’m doing stock analysis, and trying to plot returns relative to the existing closing price. I don’t understand why MPL is flatting the first plot – or how to make it stop.

Thanks for any help.

Advertisement

Answer

It’s not flattening it per se. But the scale of the second line/plot is much bigger than the first that it shows like it’s flattened.

You will need to use multiple scales (multiple y axis).

Check out this example from the matplotlib documentation.

Basically, you will need to do something like this:

...
fig, axs = plt.subplots(figsize=(20, 10), sharex=True, sharey=True)
axs.plot(close, color='black')
// same code as before above

// changed code below
ax2 = axs.twinx()
ax2.plot(test, color='blue')
fig.tight_layout()
plt.show()
plt.close()
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement