如何在 python 中制作子图?
How to make subplots in python?
我正在尝试制作子图。
我从数据框中调用许多列,将它们转换为数组并绘制它们。
我想将它们绘制成 4 行 2 列。但我只有 1 列(你可以查看图像)。我做错了什么?
这是我的代码:
for column in df3: #I call the dataframe
data=df3[column].values #Turn it into an array
fig = plt.figure()
plt.subplot (4,2,1) #I want 4 rows and 2 columns
ax,_=plot_topomap(data, sensors_pos, cmap='viridis', vmin=0, vmax=100, show=False)
plt.title("KNN" + " " + column) #This is the title for each subplot
fig.colorbar(ax)
plt.show
有几件事可能会导致您的代码出现问题,如果不了解完整代码就很难找到解决方案。
在您的代码中,您创建了多个图形。但是,您真的想要一个数字。所以图形需要在循环外创建。
然后你想创建子图,所以在每个循环步骤中你需要告诉 matplotlib 它应该绘制到哪个子图。这可以通过 ax = fig.add_subplot(4,2,n)
来完成,其中 n 是您在循环的每个 运行 中增加的数字。
接下来你打电话给 plot_topomap
。但是 plot_topomap
怎么知道在哪里绘制什么?您需要通过提供关键字参数 axes = ax
来告诉它。
最后尝试设置颜色条,将 return 图像作为坐标轴的参数 ax
。
当然我不能测试下面的代码,但它可能会做你想要的,以防我很好地解释一切。
n = 1
fig = plt.figure()
for column in df3: #I call the dataframe
data=df3[column].values #Turn it into an array
ax = fig.add_subplot(4,2,n) #I want 4 rows and 2 columns
im,_ = plot_topomap(data, sensors_pos, cmap='viridis', vmin=0, vmax=100, show=False, axes=ax)
ax.set_title("KNN" + " " + column) #This is the title for each subplot
fig.colorbar(im, ax=ax)
n+=1
我正在尝试制作子图。 我从数据框中调用许多列,将它们转换为数组并绘制它们。 我想将它们绘制成 4 行 2 列。但我只有 1 列(你可以查看图像)。我做错了什么?
这是我的代码:
for column in df3: #I call the dataframe
data=df3[column].values #Turn it into an array
fig = plt.figure()
plt.subplot (4,2,1) #I want 4 rows and 2 columns
ax,_=plot_topomap(data, sensors_pos, cmap='viridis', vmin=0, vmax=100, show=False)
plt.title("KNN" + " " + column) #This is the title for each subplot
fig.colorbar(ax)
plt.show
有几件事可能会导致您的代码出现问题,如果不了解完整代码就很难找到解决方案。
在您的代码中,您创建了多个图形。但是,您真的想要一个数字。所以图形需要在循环外创建。
然后你想创建子图,所以在每个循环步骤中你需要告诉 matplotlib 它应该绘制到哪个子图。这可以通过 ax = fig.add_subplot(4,2,n)
来完成,其中 n 是您在循环的每个 运行 中增加的数字。
接下来你打电话给 plot_topomap
。但是 plot_topomap
怎么知道在哪里绘制什么?您需要通过提供关键字参数 axes = ax
来告诉它。
最后尝试设置颜色条,将 return 图像作为坐标轴的参数 ax
。
当然我不能测试下面的代码,但它可能会做你想要的,以防我很好地解释一切。
n = 1
fig = plt.figure()
for column in df3: #I call the dataframe
data=df3[column].values #Turn it into an array
ax = fig.add_subplot(4,2,n) #I want 4 rows and 2 columns
im,_ = plot_topomap(data, sensors_pos, cmap='viridis', vmin=0, vmax=100, show=False, axes=ax)
ax.set_title("KNN" + " " + column) #This is the title for each subplot
fig.colorbar(im, ax=ax)
n+=1