サイズ8x 8の50枚の画像をサイズ64の配列にフラット化したデータセットがあります。(plt)の関数imshow
を使用してmatplotlib.pyplot
、データセットの最初の16枚の画像(4x4グリッド)を視覚化します。
次のコードを試しました。
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(50,64) #this will simulate my data
fig=plt.figure(figsize=(8, 8))
for i in range(16):
img = np.reshape(data[i:(i+1)],(8,8))
fig.add_subplot(4, 4, i)
plt.imshow(img)
plt.show()
これはトレースバックです:
<ipython-input-207-7af8d2013358> in plot_first_digits()
13
14 img = np.reshape(X[i:(i+1)],(8,8))
---> 15 fig.add_subplot(4, 4, i)
16 plt.imshow(img)
17
~/anaconda3/lib/python3.8/site-packages/matplotlib/figure.py in add_subplot(self, *args, **kwargs)
1417 self._axstack.remove(ax)
1418
-> 1419 a = subplot_class_factory(projection_class)(self, *args, **kwargs)
1420
1421 return self._add_axes_internal(key, a)
~/anaconda3/lib/python3.8/site-packages/matplotlib/axes/_subplots.py in __init__(self, fig, *args, **kwargs)
63 else:
64 if num < 1 or num > rows*cols:
---> 65 raise ValueError(
66 f"num must be 1 <= num <= {rows*cols}, not {num}")
67 self._subplotspec = GridSpec(
ValueError: num must be 1 <= num <= 16, not 0
<Figure size 576x576 with 0 Axes>
スクリプトから、エラーは最初の反復でのplt.add_subplot()
withの呼び出しが原因であることがわかりi = 0
ます(この関数は正の整数引数のみを受け入れます)。
fig.add_subplots
import matplotlib.pyplot as plt
import numpy as np
# simulate data
data = np.random.rand(50, 64)
# create figure
fig = plt.figure(figsize=(8, 8))
# loop over images
for i in range(16):
print(i)
img = np.reshape(data[i : (i + 1)], (8, 8))
fig.add_subplot(4, 4, i + 1)
plt.imshow(img)
# save image
plt.savefig("subplot_image")
出力画像は次のようになります。
plt.subplots
(よりpythonic)を使用したソリューション2次のソリューションは、生成されたサブプロットplt.subplots()
とdata
行列の要素を直接反復することにより、同じ画像を生成します。
# create figure
fig, axes = plt.subplots(4, 4, figsize=(8, 8))
# loop over images
for ax, img in zip(axes.ravel(), data):
ax.imshow(img.reshape(8, 8))
# save image
plt.savefig("subplot_image")
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加