Search code examples
pythonmatplotlibaxis-labels

How to add text "H_m" instead of 100% in yaxis matplotlib?


I'd like to add the text "H_m" instead of the 100% symbol in my y-axis and increase the fontsize in the label, but I can't figure it out. This is what I got:

import math
import itertools
import csv
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick


fig = plt.figure(3, figsize = (10,6))
ax = fig.add_subplot(1,1,1)
plt.rc('xtick', labelsize = 18)    # fontsize of the tick labels
plt.rc('ytick', labelsize = 18)    # fontsize of the tick labels
plt.grid(True)
#plt.xlim((-0.2, 2))
#plt.ylim((0, 20))
plt.xlabel(r'$t$ [s]', fontsize = 20)
plt.ylabel(r'$H_a$ [A/m]', fontsize = 20)
marker = itertools.cycle(('.', '+', 's', 'o', '*', 'v', 'H', 'D'))

X_1, Y_1 = list(), list()
### Open external file ###
with open('data-lua.dat') as csvfile:
    readCSV = csv.reader(csvfile, delimiter='\t')
    for row in readCSV:
      X_1.append(float(row[0]))
      Y_1.append(float(row[1])/7961.783439)

plt.plot(X_1, Y_1, color='k', linestyle='-', marker='o', markersize ='5')
ax.yaxis.set_major_formatter(mtick.PercentFormatter())
plt.savefig('data-lua.png', format = 'png', dpi = 300, bbox_inches = 'tight')
plt.show()

Output: Output And this is an example of what I want: Example


Solution

  • How about first normalizing your y value onto [0,1] and then use MultipleLocator(0.2) to produce 5 intervals instead?

    y = (y - y.min()) / (y.max() - y.min())
    ax.set_ylim([0,1])
    ax.yaxis.set_major_locator(mtick.MultipleLocator(0.2))
    ax.set_yticklabels(["", "0%", "20%", "40%", "60%", "80%", "$H_m$", ""])
    

    Note that MultipleLocator() adds an extra tick outside xlim range, so the length of yticklabels must be adjusted accordingly. The yticklabels looked like this:

    Imgur