bug*_*syb 116 python matplotlib subplot
我对这段代码的工作原理有点困惑:
fig, axes = plt.subplots(nrows=2, ncols=2)
plt.show()
Run Code Online (Sandbox Code Playgroud)
在这种情况下,无花果轴如何工作?它有什么作用?
为什么这不能做同样的事情:
fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)
Run Code Online (Sandbox Code Playgroud)
谢谢
小智 156
有几种方法可以做到这一点.该subplots方法创建图形以及随后存储在ax数组中的子图.例如:
import matplotlib.pyplot as plt
x = range(10)
y = range(10)
fig, ax = plt.subplots(nrows=2, ncols=2)
for row in ax:
for col in row:
col.plot(x, y)
plt.show()
Run Code Online (Sandbox Code Playgroud)
但是,这样的东西也会起作用,虽然你创建了一个包含子图的图形,然后在它们之上添加,但它并不那么"干净":
fig = plt.figure()
plt.subplot(2, 2, 1)
plt.plot(x, y)
plt.subplot(2, 2, 2)
plt.plot(x, y)
plt.subplot(2, 2, 3)
plt.plot(x, y)
plt.subplot(2, 2, 4)
plt.plot(x, y)
plt.show()
Run Code Online (Sandbox Code Playgroud)
Kha*_*oti 32
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 2)
ax[0, 0].plot(range(10), 'r') #row=0, col=0
ax[1, 0].plot(range(10), 'b') #row=1, col=0
ax[0, 1].plot(range(10), 'g') #row=0, col=1
ax[1, 1].plot(range(10), 'k') #row=1, col=1
plt.show()
Run Code Online (Sandbox Code Playgroud)
Col*_*ony 15
您也可以在子图调用中打开轴的包装
并设置是否要在子图之间共享x和y轴
像这样:
import matplotlib.pyplot as plt
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True)
ax1.plot(range(10), 'r')
ax2.plot(range(10), 'b')
ax3.plot(range(10), 'g')
ax4.plot(range(10), 'k')
plt.show()
Run Code Online (Sandbox Code Playgroud)
Diz*_*ahi 10
阅读文档:matplotlib.pyplot.subplots
pyplot.subplots()返回一个元组fig, ax,使用符号将其解压缩为两个变量
fig, axes = plt.subplots(nrows=2, ncols=2)
Run Code Online (Sandbox Code Playgroud)
代码
fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)
Run Code Online (Sandbox Code Playgroud)
不起作用,因为subplots()函数pyplot不是对象的成员Figure.
您可能对以下事实感兴趣:从matplotlib 2.1版开始,问题的第二个代码也很好用。
从更改日志:
Figure类现在具有subplots方法。Figure类现在具有subplots()方法,其行为与pyplot.subplots()相同,但在现有的地物上。
例:
import matplotlib.pyplot as plt
fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)
plt.show()
Run Code Online (Sandbox Code Playgroud)
pandaspandas,它用作matplotlib默认的绘图后端。pandas.DataFrame
python 3.8.11, pandas 1.3.2, matplotlib 3.4.3,seaborn 0.11.2import seaborn as sns # data only
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# wide dataframe
df = sns.load_dataset('planets').iloc[:, 2:5]
orbital_period mass distance
0 269.300 7.10 77.40
1 874.774 2.21 56.95
2 763.000 2.60 19.84
3 326.030 19.40 110.62
4 516.220 10.50 119.47
# long dataframe
dfm = sns.load_dataset('planets').iloc[:, 2:5].melt()
variable value
0 orbital_period 269.300
1 orbital_period 874.774
2 orbital_period 763.000
3 orbital_period 326.030
4 orbital_period 516.220
Run Code Online (Sandbox Code Playgroud)
subplots=True和layout, 对于每列subplots=True和layout=(rows, cols)pandas.DataFrame.plotkind='density',但有不同的选项kind,这适用于所有选项。如果不指定kind,则默认为线图。axAxesSubplot是返回的数组pandas.DataFrame.plotFigure对象。
axes = df.plot(kind='density', subplots=True, layout=(2, 2), sharex=False, figsize=(10, 6))
# extract the figure object; only used for tight_layout in this example
fig = axes[0][0].get_figure()
# set the individual titles
for ax, title in zip(axes.ravel(), df.columns):
ax.set_title(title)
fig.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)
plt.subplots,对于每一列Axes创建一个with数组matplotlib.pyplot.subplots,然后将axes[i, j]or传递axes[n]给ax参数。
pandas.DataFrame.plot,但可以使用其他axes级别绘图调用作为替代(例如sns.kdeplot、plt.plot等)Axes成一维是最简单的。参见与。.ravel.flatten.ravel.flattenaxes、需要迭代的变量都与.zip(例如cols、axes、colors、palette等)组合。每个对象的长度必须相同。fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10, 6)) # define the figure and subplots
axes = axes.ravel() # array to 1D
cols = df.columns # create a list of dataframe columns to use
colors = ['tab:blue', 'tab:orange', 'tab:green'] # list of colors for each subplot, otherwise all subplots will be one color
for col, color, ax in zip(cols, colors, axes):
df[col].plot(kind='density', ax=ax, color=color, label=col, title=col)
ax.legend()
fig.delaxes(axes[3]) # delete the empty subplot
fig.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)
plt.subplots,对于每个组.groupbycolor并axes指向一个.groupby对象。fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10, 6)) # define the figure and subplots
axes = axes.ravel() # array to 1D
dfg = dfm.groupby('variable') # get data for each unique value in the first column
colors = ['tab:blue', 'tab:orange', 'tab:green'] # list of colors for each subplot, otherwise all subplots will be one color
for (group, data), color, ax in zip(dfg, colors, axes):
data.plot(kind='density', ax=ax, color=color, title=group, legend=False)
fig.delaxes(axes[3]) # delete the empty subplot
fig.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)
seaborn人物级情节seaborn图形级图,并使用col或row参数。seaborn是一个高级 API matplotlib。请参阅seaborn:API 参考。p = sns.displot(data=dfm, kind='kde', col='variable', col_wrap=2, x='value', hue='variable',
facet_kws={'sharey': False, 'sharex': False}, height=3.5, aspect=1.75)
sns.move_legend(p, "upper left", bbox_to_anchor=(.55, .45))
Run Code Online (Sandbox Code Playgroud)
按顺序迭代所有子图:
fig, axes = plt.subplots(nrows, ncols)
for ax in axes.flatten():
ax.plot(x,y)
Run Code Online (Sandbox Code Playgroud)
访问特定索引:
for row in range(nrows):
for col in range(ncols):
axes[row,col].plot(x[row], y[col])
Run Code Online (Sandbox Code Playgroud)
axes为一维plt.subplots(nrows, ncols)(其中nrows 和 ncols都大于 1)会返回嵌套的<AxesSubplot:>对象数组。\naxes情况下,\xe2\x80\x99s 不需要展平,因为已经是一维了,这是默认参数的结果nrows=1ncols=1axessqueeze=True.ravel()。.flatten()\ .flatn.ravel与.flatten\nflatten总是返回一个副本。ravel尽可能返回原始数组的视图。axes转换为一维数组,就有多种绘制方法。ax=(例如sns.barplot(\xe2\x80\xa6, ax=ax[0])。\nseaborn是一个高级 API matplotlib。请参阅图级函数与轴级函数,seaborn 未在定义的子图中绘制import matplotlib.pyplot as plt\nimport numpy as np # sample data only\n\n# example of data\nrads = np.arange(0, 2*np.pi, 0.01)\ny_data = np.array([np.sin(t*rads) for t in range(1, 5)])\nx_data = [rads, rads, rads, rads]\n\n# Generate figure and its subplots\nfig, axes = plt.subplots(nrows=2, ncols=2)\n\n# axes before\narray([[<AxesSubplot:>, <AxesSubplot:>],\n [<AxesSubplot:>, <AxesSubplot:>]], dtype=object)\n\n# convert the array to 1 dimension\naxes = axes.ravel()\n\n# axes after\narray([<AxesSubplot:>, <AxesSubplot:>, <AxesSubplot:>, <AxesSubplot:>],\n dtype=object)\nRun Code Online (Sandbox Code Playgroud)\nIndexError: list index out of range\naxes[:-2])for i, ax in enumerate(axes):\n ax.plot(x_data[i], y_data[i])\nRun Code Online (Sandbox Code Playgroud)\naxes[0].plot(x_data[0], y_data[0])\naxes[1].plot(x_data[1], y_data[1])\naxes[2].plot(x_data[2], y_data[2])\naxes[3].plot(x_data[3], y_data[3])\nRun Code Online (Sandbox Code Playgroud)\nfor i in range(len(x_data)):\n axes[i].plot(x_data[i], y_data[i])\nRun Code Online (Sandbox Code Playgroud)\nzip将轴和数据放在一起,然后迭代元组列表。for ax, x, y in zip(axes, x_data, y_data):\n ax.plot(x, y)\nRun Code Online (Sandbox Code Playgroud)\nfig, (ax1, ax2, ax3) = plt.subplots(1, 3)。然而,正如所写,这只适用于 或 的nrows=1情况ncols=1。这是基于 返回的数组的形状plt.subplots,并且很快就会变得很麻烦。\nfig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)对于 2 x 2 数组。fig, (ax1, ax2) = plt.subplots(1, 2)或fig, (ax1, ax2) = plt.subplots(2, 1))最有用。对于更多子图,展平和迭代轴数组会更有效。| 归档时间: |
|
| 查看次数: |
186640 次 |
| 最近记录: |