import matplotlib.pyplot as pltimport numpy as npdef xticklabels_example():
fig = plt.figure()
x = np.arange(20)
y1 = np.cos(x)
y2 =(x**2)
y3 =(x**3)
yn =(y1,y2,y3)
COLORS =('b','g','k')for i,y in enumerate(yn):
ax = fig.add_subplot(len(yn),1,i+1)
ax.plot(x, y, ls='solid', color=COLORS[i])if i != len(yn)-1:# all but last
ax.set_xticklabels(())else:for tick in ax.xaxis.get_major_ticks():
tick.label.set_fontsize(14)# specify integer or one of preset strings, e.g.#tick.label.set_fontsize('x-small')
tick.label.set_rotation('vertical')
fig.suptitle('Matplotlib xticklabels Example')
plt.show()if __name__ =='__main__':
xticklabels_example()
Please note that newer versions of MPL have a shortcut for this task. An example is shown in the other answer to this question: https://stackoverflow.com/a/11386056/42346
The code below is for illustrative purposes and may not necessarily be optimized.
import matplotlib.pyplot as plt
import numpy as np
def xticklabels_example():
fig = plt.figure()
x = np.arange(20)
y1 = np.cos(x)
y2 = (x**2)
y3 = (x**3)
yn = (y1,y2,y3)
COLORS = ('b','g','k')
for i,y in enumerate(yn):
ax = fig.add_subplot(len(yn),1,i+1)
ax.plot(x, y, ls='solid', color=COLORS[i])
if i != len(yn) - 1:
# all but last
ax.set_xticklabels( () )
else:
for tick in ax.xaxis.get_major_ticks():
tick.label.set_fontsize(14)
# specify integer or one of preset strings, e.g.
#tick.label.set_fontsize('x-small')
tick.label.set_rotation('vertical')
fig.suptitle('Matplotlib xticklabels Example')
plt.show()
if __name__ == '__main__':
xticklabels_example()
回答 1
实际上有一个更简单的方法。我刚刚发现:
import matplotlib.pyplot as plt# We prepare the plot
fig, ax = plt.subplots()# We change the fontsize of minor ticks label
ax.tick_params(axis='both', which='major', labelsize=10)
ax.tick_params(axis='both', which='minor', labelsize=8)
import matplotlib.pyplot as plt
# We prepare the plot
fig, ax = plt.subplots()
# We change the fontsize of minor ticks label
ax.tick_params(axis='both', which='major', labelsize=10)
ax.tick_params(axis='both', which='minor', labelsize=8)
This only answers to the size of label part of your question though.
I have two plots side by side and would like to adjust tick labels separately.
The above solutions were close however they were not working out for me. I found my solution from this matplotlib page.
ax.xaxis.set_tick_params(labelsize=20)
This did the trick and was straight to the point. For my use case, it was the plot on the right that needed to be adjusted. For the plot on the left since I was creating new tick labels I was able to adjust the font in the same process as seting the labels.