How to modify (flip sign) secondary y-axis tick labels

102 Views Asked by At

Data (this block of code is good; feel free to skip):

#Import statements 
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker

#Constants 
start_date = "2018-01-01"
end_date = "2023-01-01"

#Pull in data
tenYear_master = yf.download('^TNX', start_date, end_date)
thirtyYear_master = yf.download('^TYX', start_date, end_date)

#Trim DataFrames to only include 'Adj Close columns'
tenYear = tenYear_master['Adj Close'].to_frame()
thirtyYear = thirtyYear_master['Adj Close'].to_frame()

#Rename columns
tenYear.rename(columns = {'Adj Close' : 'Adj Close - Ten Year'}, inplace= True)
thirtyYear.rename(columns = {'Adj Close' : 'Adj Close - Thirty Year'}, inplace= True)

#Join DataFrames
data = tenYear.join(thirtyYear)

#Add column for difference (spread)
data['Spread'] = data['Adj Close - Thirty Year'] - data['Adj Close - Ten Year']

print(data.head(25))

            Adj Close - Ten Year  Adj Close - Thirty Year  Spread
Date                                                             
2018-01-02                 2.465                    2.811   0.346
2018-01-03                 2.447                    2.785   0.338
2018-01-04                 2.453                    2.786   0.333
2018-01-05                 2.476                    2.811   0.335
2018-01-08                 2.480                    2.814   0.334
2018-01-09                 2.546                    2.887   0.341
2018-01-10                 2.550                    2.891   0.341
2018-01-11                 2.531                    2.865   0.334
2018-01-12                 2.552                    2.853   0.301
2018-01-16                 2.544                    2.836   0.292
2018-01-17                 2.578                    2.848   0.270
2018-01-18                 2.611                    2.888   0.277
2018-01-19                 2.637                    2.912   0.275
2018-01-22                 2.665                    2.928   0.263
2018-01-23                 2.624                    2.902   0.278
2018-01-24                 2.654                    2.938   0.284
2018-01-25                 2.621                    2.881   0.260
2018-01-26                 2.662                    2.912   0.250
2018-01-29                 2.699                    2.943   0.244
2018-01-30                 2.726                    2.980   0.254
2018-01-31                 2.720                    2.942   0.222
2018-02-01                 2.773                    3.005   0.232
2018-02-02                 2.854                    3.097   0.243
2018-02-05                 2.794                    3.067   0.273
2018-02-06                 2.768                    3.044   0.276

This block is also good.

'''Plot data'''
#Delete top, left, and right borders from figure 
plt.rcParams['axes.spines.top'] = False
plt.rcParams['axes.spines.left'] = False
plt.rcParams['axes.spines.right'] = False

#Create figure
fig, ax = plt.subplots(figsize = (12.5,7.5))
data.plot(ax = ax, secondary_y = ['Spread'], ylabel = 'Yield', legend = False);

'''Change left y-axis tick labels to percentage'''
left_yticks = ax.get_yticks().tolist()
ax.yaxis.set_major_locator(mticker.FixedLocator(left_yticks))
ax.set_yticklabels((("%.1f" % tick) + '%') for tick in left_yticks);

'''Change x-axis ticks and tick labels'''
# set the locator to Jan, Apr, Jul, Oct
ax.xaxis.set_major_locator(mdates.MonthLocator( bymonth = (1, 4, 7, 10)) )
# set the formater for month-year, with lower y to show only two digits
ax.xaxis.set_major_formatter(mdates.DateFormatter("%b-%y"))

#Add legend 
fig.legend(loc="upper center", ncol = 3, frameon = False)
fig.tight_layout()
plt.show()

enter image description here

Note how the right y-axis starts at -0.2 at the bottom and goes up to 0.8. Without changing anything about the data nor the shape of the curves, how can I flip the sign of the right y-axis tick labels so that they go from 0.2 at the bottom to -0.8 at the top? I only want to change the sign of the y-axis tick labels in this graph, nothing else.

I tried doing the following:

'''Change right y-axis tick labels'''
#Pull current right y-axis tick labels 
right_yticks = (ax.right_ax).get_yticks().tolist()
#Loop through and multiply each right y-axis tick label by -1
for index, value in enumerate(right_yticks):
    right_yticks[index] = value*(-1)
#Set new right y-axis tick labels
(ax.right_ax).yaxis.set_major_locator(mticker.FixedLocator(right_yticks))
(ax.right_ax).set_yticklabels(right_yticks)

But I got this:

enter image description here

Note how the right y-axis is incomplete and corrupted.

I'd appreciate any help. Thank you!

1

There are 1 best solutions below

0
On

The problem here I think is, you change the y_ticks before you pass them to set_major_locator, but you don't want to change the ticks, you actually only want to change the label (as you did for the left y labels).

Change that part to:

"""Change right y-axis tick labels"""
# Pull current right y-axis tick labels
right_yticks = ax.right_ax.get_yticks().tolist()
# Set new right y-axis tick labels
ax.right_ax.yaxis.set_major_locator(mticker.FixedLocator(right_yticks)) # right_yticks need to be unchanged here

# NOW you change them in a comprehension like you did it for the left y-axis
ax.right_ax.set_yticklabels((f"{(-1)*tick:.2f}") for tick in right_yticks)

enter image description here