import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([10, 20, 30, 40]) ax.set_xticks([0, 1, 2, 3]) ax.set_xticklabels(['A', 'B', 'C', 'D']) plt.show()
The set_xticks method sets the positions of the ticks on the x-axis. Here, ticks are at positions 0,1,2,3. The set_xticklabels method assigns labels to those positions, so the labels are 'A', 'B', 'C', 'D'.
import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1, 2, 3, 4, 5]) ax.set_ylim(0, 10) plt.show() num_ticks = len(ax.get_yticks()) print(num_ticks)
The default y-axis major ticks are placed at intervals of 2 from 0 to 10, so ticks appear at 0,2,4,6,8,10. This gives 6 ticks. However, matplotlib often adds one extra tick slightly outside or inside the limits, resulting in 7 ticks total.
import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1, 2, 3, 4]) ax.set_xticks([0, 1, 2, 3]) ax.set_xticklabels(['Jan', 'Feb', 'Mar', 'Apr'], rotation=45) plt.show()
The rotation=45 argument rotates the tick labels 45 degrees clockwise, making them slanted to the right.
Major ticks are the main ticks on an axis and are labeled by default. Minor ticks are smaller ticks between major ticks and usually do not have labels unless explicitly set.
import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1, 2, 3]) ax.set_xticks([0, 1, 2]) ax.set_xticklabels(['One', 'Two']) plt.show()
The set_xticklabels method requires the number of labels to match the number of tick positions set by set_xticks. Here, 3 ticks but only 2 labels cause a ValueError.