在python matplotlib中,有两种用于绘制绘图的约定:
1.再分配
plt.figure(1,figsize=(400,8))2.再分配
fig,ax = plt.subplots()
fig.set_size_inches(400,8)两者都有不同的方式来做同样的事情。例如定义轴标签。
哪一种更适合使用?一个相对于另一个有什么优势?或者使用matplotlib绘制图形的“良好实践”是什么?
发布于 2020-08-31 07:08:26
尽管@tacaswell已经对关键的区别作了简短的评论。我只会根据我自己在matplotlib方面的经验来补充这个问题。
plt.figure只创建一个Figure (但其中没有Axes ),这意味着您必须指定ax来放置数据(行、散点、图像)。最低限度代码应该如下所示:
import numpy as np
import matplotlib.pyplot as plt
# create a figure
fig = plt.figure(figsize=(7.2, 7.2))
# generate ax1
ax1 = fig.add_axes([0.1, 0.1, 0.5, 0.5])
# generate ax2, make it red to distinguish
ax2 = fig.add_axes([0.6, 0.6, 0.3, 0.3], fc='red')
# add data
x = np.linspace(0, 2*np.pi, 20)
y = np.sin(x)
ax1.plot(x, y)
ax2.scatter(x, y)在plt.subplots(nrows=, ncols=)的例子中,您将得到Figure和一个Axes(AxesSubplot)数组。它主要用于同时生成多个子样地。一些示例代码:
def display_axes(axes):
for i, ax in enumerate(axes.ravel()):
ax.text(0.5, 0.5, s='ax{}'.format(i+1), transform=ax.transAxes)
# create figures and (2x2) axes array
fig, axes = plt.subplots(2, 2, figsize=(7.2, 7.2))
# four (2*2=4) axes
ax1, ax2, ax3, ax4 = axes.ravel()
# for illustration purpose
display_axes(axes)摘要:
https://stackoverflow.com/questions/29619149
复制相似问题