cad*_*ams 3 python plot matplotlib
我正在尝试创建一个很好的图,它连接了一个 4x4 的子图网格(与 gridspec 一起放置,每个子图为 8x8 像素)。我一直在努力使情节之间的间距与我试图告诉它做的事情相匹配。我想问题是由于在图的右侧绘制了一个颜色条,并调整了图中图的位置以适应。然而,即使没有包含颜色条,这个问题似乎也会出现,这让我更加困惑。它也可能与边距有关。下面显示的图像是由相关代码生成的。正如你所看到的,我试图让图之间的空间变为零,但它似乎不起作用。任何人都可以建议吗?
fig = plt.figure('W Heat Map', (18., 15.))
gs = gridspec.GridSpec(4,4)
gs.update(wspace=0., hspace=0.)
for index in indices:
loc = (i,j) #determined by the code
ax = plt.subplot(gs[loc])
c = ax.pcolor(physHeatArr[index,:,:], vmin=0, vmax=1500)
# take off axes
ax.axis('off')
ax.set_aspect('equal')
fig.subplots_adjust(right=0.8,top=0.9,bottom=0.1)
cbar_ax = heatFig.add_axes([0.85, 0.15, 0.05, 0.7])
cbar = heatFig.colorbar(c, cax=cbar_ax)
cbar_ax.tick_params(labelsize=16)
fig.savefig("heatMap.jpg")
Run Code Online (Sandbox Code Playgroud)
同样,在制作没有颜色条的方形图形时:
fig = plt.figure('W Heat Map', (15., 15.))
gs = gridspec.GridSpec(4,4)
gs.update(wspace=0., hspace=0.)
for index in indices:
loc = (i,j) #determined by the code
ax = plt.subplot(gs[loc])
c = ax.pcolor(physHeatArr[index,:,:], vmin=0, vmax=400, cmap=plt.get_cmap("Reds_r"))
# take off axes
ax.axis('off')
ax.set_aspect('equal')
fig.savefig("heatMap.jpg")
Run Code Online (Sandbox Code Playgroud)
当轴纵横比设置为不自动调整(例如使用set_aspect("equal")或 数字纵横比,或一般使用imshow)时,即使wspace和hspace设置为,子图之间也可能存在一些空白0。为了消除图形之间的空白,您可以查看以下问题
您可以首先考虑第一个问题的这个答案,其中的解决方案是从单个数组中构建一个数组,然后使用pcolor,pcolormesh或绘制这个单个数组imshow。这使得稍后添加颜色条变得特别舒服。
否则,请考虑设置 figuresize 和 subplot 参数,以便不会留下 whitespae。在第二个问题的答案中可以找到该计算的公式。
带有颜色条的改编版本如下所示:
import matplotlib.pyplot as plt
import matplotlib.colors
import matplotlib.cm
import numpy as np
image = np.random.rand(16,8,8)
aspect = 1.
n = 4 # number of rows
m = 4 # numberof columns
bottom = 0.1; left=0.05
top=1.-bottom; right = 1.-0.18
fisasp = (1-bottom-(1-top))/float( 1-left-(1-right) )
#widthspace, relative to subplot size
wspace=0 # set to zero for no spacing
hspace=wspace/float(aspect)
#fix the figure height
figheight= 4 # inch
figwidth = (m + (m-1)*wspace)/float((n+(n-1)*hspace)*aspect)*figheight*fisasp
fig, axes = plt.subplots(nrows=n, ncols=m, figsize=(figwidth, figheight))
plt.subplots_adjust(top=top, bottom=bottom, left=left, right=right,
wspace=wspace, hspace=hspace)
#use a normalization to make sure the colormapping is the same for all subplots
norm=matplotlib.colors.Normalize(vmin=0, vmax=1 )
for i, ax in enumerate(axes.flatten()):
ax.imshow(image[i, :,:], cmap = "RdBu", norm=norm)
ax.axis('off')
# use a scalarmappable derived from the norm instance to create colorbar
sm = matplotlib.cm.ScalarMappable(cmap="RdBu", norm=norm)
sm.set_array([])
cax = fig.add_axes([right+0.035, bottom, 0.035, top-bottom])
fig.colorbar(sm, cax=cax)
plt.show()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4640 次 |
| 最近记录: |