1

I want to increase the ticks fontsize on a plot (both x and y axes) without passing labels as an input argument to ax.set_yticklabels()

For example, say I have the y-data below (x-data doesn't matter for this example, so you could set x=np.arange(len(y)))

import numpy as np
import matplotlib.pylab as plt
y = np.array([ 5840.5,  3579.5,  2578. ,   965.5,   748. ,   485. ])
fig,ax = plt.subplots(figsize=(12,8))
plt.plot(np.arange(len(y)), y)
plt.show()

enter image description here

Now what I would like to do is increase the fontsize of the y-ticks, but I want to leave the labels the same and in the same location as matplotlib has created them. So I tried

ax.set_yticklabels(fontsize=20)
>>> TypeError: set_yticklabels() missing 1 required positional argument: 'labels'

which of course doesn't work. But if I pass some labels as an argument

y = np.array([ 5840.5,  3579.5,  2578. ,   965.5,   748. ,   485. ])
fig,ax = plt.subplots(figsize=(12,8))
plt.plot(np.arange(len(y)), y)
ax.set_yticklabels(np.arange(0,y.max(),1000), fontsize=20)
plt.show()

enter image description here

the fontsize does increase, but the labels and scale aren't the same as the original plot. I need to be able to change the fontsize for any array y, not just this example given above, so passing a specific label isn't possible.

Ideally what I want looks like this: the same labels and scale as in the first plot, but the y-ticks fontsize is larger. I want to produce this plot without passing labels each time I plot, because my x and y variables are dynamic. Is there a way to do this? enter image description here

PyRsquared
  • 6,970
  • 11
  • 50
  • 86
  • Duplicate of [this one](https://stackoverflow.com/questions/6390393/matplotlib-make-tick-labels-font-size-smaller). There are several other links which address this problem. Here is another one [here](https://stackoverflow.com/questions/45710545/how-to-change-xticks-font-size-in-a-matplotlib-plot) – Sheldore Aug 30 '18 at 09:50
  • See especially [this answer](https://stackoverflow.com/a/11386056/4124317) for the purpose. – ImportanceOfBeingErnest Aug 30 '18 at 10:03

2 Answers2

4

You can set the ytick rc param which will change the ytick fontsize for each subsequent plot using:

import matplotlib
matplotlib.rc('ytick', labelsize=20)

Alternatively if you want to do this for only one figure, you can loop through each label and change the fontsize:

for label in ax.get_yticklabels():
    label.set_fontsize(20)
DavidG
  • 24,279
  • 14
  • 89
  • 82
1

You can use plt.yticks() as follows:

fig,ax = plt.subplots(figsize=(12,8))
plt.plot(np.arange(len(y)), y)
plt.yticks(fontsize=20)

plt.show()
abc
  • 11,579
  • 2
  • 26
  • 51