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


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


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.


# Equivalent methods for plot and axes



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?

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.


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

1 Like

I am getting following warning:
c:\pyproj\venv\lib\site-packages\ MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.

Hi @soniamehta9360925842.

I believe that error occurs when you’ve effectively called for axis creation twice. At this moment this behaviour is allowed but in the future it is likely to be changed and therefore you should always alter existing objects with their own methods. I dont know exactly what code you used but here’s a quick example-

# create a figure and axis instance and assign them to fig and ax
fig, ax = plt.subplots(1, 1)
# adjust the axis limits with pyplot convenience function
plt.axis([0, 10, 20, 100])  # alters the already created axis
# WARNING!! In the future this may instead create a new axis instance

Instead it would be good to get in the habit now of relying on instance methods and such (doubly so due to the deprecation warning), exmple below-

fig, ax = plt.subplots(1, 1)
# documentaiton suggested equivalent-
# ax.set(xlim=(xmin, xmax), ylim=(ymin, ymax))
ax.set(xlim=(0, 10), ylim=(20, 200))

Matplotlib Documentation is very confusing and is not planned documentation. It is hard to find proper function parameter help.

As of now, I am focusing non-oops way to plot. After I am done, I would like to do OOPS way as you guided me.

1 Like