17

I am trying to label both y-axis, one to say "WLL", the other to say "S&P 500". Right now, I can only label the secondary y-axis (S&P 500).

import pandas as pd
from pandas import DataFrame
from matplotlib import pyplot as plt
import pandas.io.data as web
import datetime as dt

start = '2013-01-01'
end = dt.datetime.today()

df = web.DataReader('WLL', 'yahoo', start, end)
sp = web.DataReader('^GSPC', 'yahoo', start, end)

fig, ax1 = plt.subplots()
df['Close'].plot(ax=ax1,color='g',linewidth=1.0)
sp['Close'].plot(secondary_y=True, ax=ax1,color='b',linewidth=1.0)
ax = df['Close'].plot(); sp['Close'].plot(ax=ax, secondary_y=True)

plt.xlabel('xlabel', fontsize=10)
plt.ylabel('ylabel', fontsize=10)

plt.show()
Brian
  • 715
  • 4
  • 16
  • 37

2 Answers2

17

just add right_ax before set_ylabel() like so:

ax.right_ax.set_ylabel()
foglerit
  • 7,792
  • 8
  • 44
  • 64
11

Edited to use pandas datareader instead of pandas.io

This can be achieved be setting the label before plotting the secondary y-axis.

from matplotlib import pyplot as plt
import pandas as pd
import pandas_datareader.data as web
from matplotlib import pyplot as plt
import datetime as dt

# Get data.
start = '2013-01-01'
end = dt.datetime.today()
df = web.DataReader('WLL', 'yahoo', start, end)
sp = web.DataReader('^GSPC', 'yahoo', start, end)

# Plot data.
ax = df['Close'].plot(ylabel='WLL', fontsize=10)
sp['Close'].plot(ax=ax, secondary_y=True)
plt.ylabel('S&P 500', fontsize=10, rotation=-90)
plt.show()

enter image description here

Alexander
  • 105,104
  • 32
  • 201
  • 196
  • You're plotting `sp['Close']` twice, once on `ax` and once on `ax1`? What does that do? Does it force alignment of the tick locators or something? Thanks. – PatrickT Jan 14 '22 at 10:10
  • 1
    I basically copied the OP's original code and made a few modifications to get it to work as intended. See above edit for a more recent example. – Alexander Jan 14 '22 at 18:38
  • 1
    Thank you Alexander, that's great! :-) – PatrickT Jan 14 '22 at 20:25
  • Wow you really predicted the stock market accurately way back in 2015! ;) – johnDanger Apr 25 '22 at 16:44