Set shared chart defaults, write returns as percentages on the axis, show wealth on a logarithmic scale, and point an arrow at one observation in matplotlib.
After this lesson, you can format a wealth chart for an article, with percentages on the axis, a logarithmic scale where growth compounds, and an arrow at the observation the text discusses.
How do I show returns as percentages on the axis?
ax.yaxis.set_major_formatter(PercentFormatter(xmax=1, decimals=0)) writes each tick of a decimal return as a percentage, so 0.5 appears as 50%, while the data stay decimals. MultipleLocator(0.5) puts the ticks 50 percentage points apart, and AAA’s cumulative return reaches 300% in 2024, when its wealth is 4 dollars.
\[
R_t = \frac{W_t}{W_0} - 1
\]
Here \(W_t\) is the wealth at the end of year \(t\) and \(W_0\) the starting wealth of 1 dollar at the end of 2022. The made-up wealth paths of AAA and BBB assume reinvested dividends and no trading costs. plt.rcParams.update sets the font size and figure size once for every chart on the page, and ax.set() sets several labels in one call.
The following box sets the defaults and draws the cumulative returns.
A logarithmic scale gives equal heights to equal proportional changes, so ax.set_yscale("log", base=2) draws AAA’s doubling from 1 to 2 dollars as tall as its doubling from 2 to 4, while a linear scale draws the second move twice as tall. A log scale suits wealth that compounds over many years.
LogLocator(base=2) puts the ticks at powers of 2, and StrMethodFormatter("${x:g}") writes them as dollar amounts, such as $2. A log scale needs positive values, so it fits wealth and not returns.
The following box draws the wealth on a base-2 log scale and prints AAA’s yearly growth factors.
ax.annotate("AAA peak", xy=(2024, 4), xytext=(2022.5, 3.5), arrowprops={"arrowstyle": "->"}) writes the text at xytext and draws an arrow to the point xy, here AAA’s peak of 4 dollars in 2024. ax.text writes a note at a point without an arrow.
Both pairs of coordinates use the units of the data. A second vertical axis from ax.twinx() for a series in other units can make two lines seem to move together, because each axis’s range sets the steepness of its line, so two panels side by side are the safer choice.
The following box draws the wealth with the arrow and a note.