figure.add_subplot() vs pyplot.subplot()

两盒软妹~` 提交于 2019-12-03 16:45:00

问题


What is the difference between add_subplot() and subplot()? They both seem to add a subplot if one isn't there. I looked at the documentation but I couldn't make out the difference. Is it just for making future code more flexible?

For example:

fig = plt.figure()
ax = fig.add_subplot(111)

vs

plt.figure(1)
plt.subplot(111)

from matplotlib tutorials.


回答1:


If you need a reference to ax for later use:

ax = fig.add_subplot(111)

gives you one while with:

plt.subplot(111)

you would need to do something like:

ax = plt.gca()

Likewise, if want to manipulate the figure later:

fig = plt.figure()

gives you a reference right away instead of:

fig = plt.gcf()

Getting explicit references is even more useful if you work with multiple subplots of figures. Compare:

figures = [plt.figure() for _ in range(5)]

with:

figures = []
for _ in range(5):
    plt.figure()
    figures.append(plt.gcf())



回答2:


pyplot.subplot is wrapper of Figure.add_subplot with a difference in behavior. Creating a subplot with pyplot.subplot will delete any pre-existing subplot that overlaps with it beyond sharing a boundary. If you do not want this behavior, use the Figure.add_subplot method or the pyplot.axes function instead. More



来源:https://stackoverflow.com/questions/34442283/figure-add-subplot-vs-pyplot-subplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!