Matplotlib madness…
JavaScript
x
19
19
1
dfin = pd.read_csv(inputfilename, sep=";", encoding='ISO-8859-1')
2
3
# create a return column
4
dfin['return'] = dfin['close'].shift(9) / dfin['close'].shift(12)
5
# create a cumulative sum column
6
dfin['return_cum'] = dfin['return'].cumsum()
7
8
9
close = dfin.iloc[:-1]['close']
10
test = dfin.iloc[:-1]['close'] * dfin.iloc[:-1]['return']
11
12
13
fig, axs = plt.subplots(figsize=(20, 10), sharex=True, sharey=True)
14
axs.plot(close, color='black')
15
axs.plot(test, color='blue')
16
plt.show()
17
plt.close()
18
19
However, when I try to run a cumulative plot of any kind, MPL flattens the first plot and plots the second relative to it:
JavaScript
1
2
1
test = dfin.iloc[:-1]['close'] * dfin.iloc[:-1]['return_cum']
2
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:
JavaScript
1
12
12
1
2
fig, axs = plt.subplots(figsize=(20, 10), sharex=True, sharey=True)
3
axs.plot(close, color='black')
4
// same code as before above
5
6
// changed code below
7
ax2 = axs.twinx()
8
ax2.plot(test, color='blue')
9
fig.tight_layout()
10
plt.show()
11
plt.close()
12