Your code example worked. I can now switch between two Y-axis plots; however, corresponding X-axis doesn’t update. Here’s my current code.
today = str(date.today())
sp_symbol = ‘^GSPC’
spfile = "C:/Users/Notebook/Desktop/Data/S&P 500 " + today + “.csv”
sp_df = pd.read_csv(spfile)
sp_df[‘Date’] = pd.to_datetime(sp_df[‘Date’])
sp_df = sp_df.sort_values(‘Date’, ascending=True)
russ_symbol = ‘^RUT’
russfile = "C:/Users/Notebook/Desktop/Data/Russell 2000 " + today + “.csv”
rus_df = pd.read_csv(russfile)
rus_df[‘Date’] = pd.to_datetime(rus_df[‘Date’])
rus_df = rus_df.sort_values(‘Date’, ascending=True)
inv_yld_crv_symbol = “Yield Curve”
iyc_file = "C:/Users/Notebook/Desktop/Data/Treasury Yield Curve " + today + “.csv”
inv_yld_crv_df = pd.read_csv(iyc_file)
inv_yld_crv_df[‘Date’] = pd.to_datetime(inv_yld_crv_df[‘Date’])
inv_yld_crv_df = inv_yld_crv_df.sort_values(‘Date’, ascending=True)
inv_yld_crv_df[‘Diff_10Y_Minus_3M’] = inv_yld_crv_df[‘10 YR’] - inv_yld_crv_df[‘3 MO’]
start_date = ‘1990-01-01’
end_date = ‘2022-01-01’
sp_df = sp_df[(sp_df[‘Date’] >= start_date) & (sp_df[‘Date’] < end_date)]
rus_df = rus_df[(rus_df[‘Date’] >= start_date) & (rus_df[‘Date’] < end_date)]
lines = {}
fig, ax = plt.subplots(figsize=(15, 7))
fig.tight_layout()
ax.plot(sp_df[‘Date’], sp_df[‘Close’], color=‘red’, label=sp_symbol)
ax.legend(loc=‘upper left’)
This creates the two different Y-axis plots that I switch between.
ax2 = ax.twinx()
lines[‘Russell 2000’], = ax2.plot(rus_df[‘Date’], rus_df[‘Close’], color=‘blue’, label=russ_symbol)
lines[‘Yield Curve’], = ax2.plot(inv_yld_crv_df[‘Date’], inv_yld_crv_df[‘Diff_10Y_Minus_3M’], color=‘green’, label=inv_yld_crv_symbol)
plt.subplots_adjust(left=0.2)
axcolor = ‘lightgoldenrodyellow’
rax = plt.axes([0.05, 0.7, 0.10, 0.10], facecolor=axcolor)
radio = RadioButtons(rax, (‘Russell 2000’, ‘Yield Curve’))
def toggle(label):
for ln in lines.values():
ln.set_visible(False)
This works, but the corresponding X-axis doesn’t change with it. Is there something I have to do to change X-axis as well?
lines[label].set_visible(True)
ax.set_title("S&P 500 vs. " + label)
ax2.legend(loc="lower right")
fig.canvas.draw_idle()
radio.on_clicked(toggle)
toggle(‘Russell 2000’)
plt.show()