Can we apply tick marks in Matplotlib without creating an Axes?

Question

Can we apply tick marks in Matplotlib without creating an Axes?

Answer

If you have more than one axes axis, you should usually apply ticks directly to each axes one. However, if you only have one plot, then you do not have to create and apply to an axes axis, but instead just apply to the entire plot area directly.

Many of the functions you apply to axes like set_xticks have an equivalent when applying to the entire plot. Usually, their equivalents require just adding set_ for the beginning of the method for axes.

Examples

# Equivalent methods for plot and axes
plt.xticks()
ax.set_xticks()

plt.xticklabels()
ax.set_xticklabels()

plt.xlabel()
ax.set_xlabel()
2 Likes

Yes, we can. For a single plot, we can do it in a single line of code for each:
plt.xticks(months, month_names)
plt.yticks([0.10, 0.25, 0.5, 0.75], ['10%', '25%', '50%', '75%']))
Isn’t it simpler?

7 Likes
plt.set_xticks(months)
plt.set_xticklabels(month_names)
plt.set_yticks([0.10, 0.25, 0.5, 0.75])
plt.set_yticklabels(["10%", "25%", "50%", "75%"])

this code say ‘module’ have no attribute ‘set_xticks’

What is the purpose of ticks in matplotlib? @mtf @appylpye

Hi @tag3272764692,

Ticks enable one to see precisely where the values apply along the axes of a graph.

1 Like

It should be ax.set…(name) as below:
ax.set_xticks(months)
ax.set_xticklabels(month_names)
ax.set_yticks([0.10, 0.25, 0.5, 0.75])
ax.set_yticklabels([“10%”, “25%”, “50%”, “75%”]