npross
npross

Reputation: 1888

When should you use ax. in matplotlib?

I still don't understand the best usage of fig, plt. and ax. in matplotlib Should I be using plt. all the time? When should ax. be used?

Upvotes: 1

Views: 2108

Answers (1)

Nils Werner
Nils Werner

Reputation: 36805

Use fig and ax are part of the object oriented interface and should be used as often as possible.

Using the old plt interface works in most cases too, but when you create and manipulate many figures or axes it can become quite tricky to keep track of all your figures:

plt.figure()
plt.plot(...)      # this implicitly modifies the axis created beforehand
plt.xlim([0, 10])  # this implicitly modifies the axis created beforehand
plt.show()

compared to

fig, ax = plt.subplots(1, 1)
ax.plot(...)           # this explicitly modifies the axis created beforehand
ax.set_xlim([0, 10])   # this explicitly modifies the axis created beforehand
plt.show()

Upvotes: 1

Related Questions