Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fig.gca() vs. fig.add_subplot()

Tags:

Most examples of object-oriented matplotlib get an Axis object with something like

import matplotlib.pyplot as plt  fig1 = plt.figure() ax1 = fig1.add_subplot(111)  ax1.plot(...... etc. 

Which I've always found to be non-obvious, especially from a matlab-perspective. I recently found that equivalent results can be obtained via

ax1 = fig1.gca()   # "GetCurrentAxis" 

Which makes way more sense to me (possibly only due to prior Matlab use). Why is add_subplot() with a confusing 111 argument chosen as the preferred way to get an axis object? Is there any functional difference?

Thanks!

like image 367
Demis Avatar asked Dec 01 '14 02:12

Demis


People also ask

What is fig GCA?

Figure. gca() method. The gca() method figure module of matplotlib library is used to get the current axes. Syntax: gca(self, **kwargs)

What does GCA mean in Matplotlib?

gca means "get current axes". "Current" here means that it provides a handle to the last active axes. If there is no axes yet, an axes will be created. If you create two subplots, the subplot that is created last is the current one.

What does Fig Add_axes?

add_axes() function. The add_axes() method figure module of matplotlib library is used to add an axes to the figure.

How do you extend the distance between two subplots in Python?

You can use plt. subplots_adjust to change the spacing between the subplots.


2 Answers

plt.gca gets the current axes, creating one if needed. It is only equivalent in the simplest 1 axes case.

The preferred way is to use plt.subplots (and the docs/examples are indeed lagging a bit, if you want to start contributing, updating the docs is a great place to start):

fig, ax = plt.subplots(1, 1) 

or

fig, (ax1, ax2) = plt.subplots(2, 1) 

and so on.

like image 167
tacaswell Avatar answered Sep 18 '22 13:09

tacaswell


To creat 3D instance, there are three ways:

plt.gca(projection='3d')  plt.subplot(projection='3d')  fig = plt.figure() fig.add_subplot(111, projection='3d')  

Maybe the third way is more complex.

like image 45
yzy_1996 Avatar answered Sep 22 '22 13:09

yzy_1996