Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
677 views
in Technique[技术] by (71.8m points)

matplotlib - How does plt.gca work internally

I have searched on google but didn't get an answer. I created a subplot consisting of 2 axes and called plt.gca() but every time it only referred to the last axis in the axes of my subplots. I then started to wonder if it is possible to get a particular axis by passing in some kwargs but didn't find such parameter. I would really like to know how plt.gca() works and why you can't specify which axis to get.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

There is no such thing as gca(something), because that would translate into "get current axes which is not the current one" - sound unlogical already, doesn't it?

The easiest way to make sure you have a handle to any axes in the plot is to create that handle yourself. E.g.

ax = plt.subplot(121)
ax2 = plt.subplot(122)

You may then use ax or ax2 at any point after that to manipulate the axes of choice.

Also consider using the subplots (note the s) command,

fig, (ax, ax2) = plt.subplots(ncols=2)

If you don't have a handle or forgot to create one, you may get one e.g. via

all_axes = plt.gcf().get_axes()
ax = all_axes[0]

to get the first axes. Since there is no natural order of axes in a plot, this should only be used if no other option is available.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...