我尝试为数据数组中的子图设置标题。
我期望的是图中的 (00, 01, 10 和 11) 位置的 Title-1、Title-2 ... 等等。
所以我做了;
import matplotlib.pyplot as plt
title = [1,2,3,4]
fig, ax = plt.subplots(2, 2, figsize=(6, 8))
for i in range(len(ax)):
for j in range(len(ax[i])):
for k in title:
# print (k)
ax[i,j].set_title('Title-' + str(k))
Run Code Online (Sandbox Code Playgroud)
但只获得了 Title-4。我该如何解决这个问题?谢谢
一种方法使用flatten和enumerate:
import matplotlib.pyplot as plt
title = [1,2,3,4]
fig, ax = plt.subplots(2, 2, figsize=(6, 8))
flat_ax = ax.flatten()
for n, ax in enumerate(flat_ax):
ax.set_title(f'Title-{title[n]}')
Run Code Online (Sandbox Code Playgroud)
输出:
另一种选择是使用iterwith flatten:
import matplotlib.pyplot as plt
title = [1,2,3,4]
ititle = iter(title)
fig, ax = plt.subplots(2, 2, figsize=(6, 8))
flat_ax = ax.flatten()
for ax in flat_ax:
ax.set_title(f'Title-{next(ititle)}')
Run Code Online (Sandbox Code Playgroud)
另外,请注意我使用的 f-string 需要 python 3.6+