How does plt.gca work internally

前端 未结 2 1461
暖寄归人
暖寄归人 2020-12-14 12:34

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 ax

2条回答
  •  有刺的猬
    2020-12-14 12:41

    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.

提交回复
热议问题