保存图形时颜色条无法完整显示
下面是我从 PyHOGS 学到的代码示例:
cmap = plt.cm.Spectral
# Generate some fake data
N = 100
nlines = 10
x = np.linspace(-np.pi, np.pi, N)
y = np.linspace(-np.pi, np.pi, nlines)
# Use np.newaxis to create [N,1] and [1,Nlines] x and y arrays
# Then broadcasting to generate Z with shape [N,Nlines]
z = np.sin(x[:,np.newaxis] + y[np.newaxis,:]/4)
# Use 0-1 values to generate the colors with the linspace method
line_colors = cmap(np.linspace(0,1,nlines))
# because the custom axes generation is the only way I've
# figured out.
from matplotlib.gridspec import GridSpec
fig = plt.figure(figsize = (12,6))
nrows = 2
gs = GridSpec(nrows,2,width_ratios=[50,1])
ax = [plt.subplot(gs[i,0]) for i in range(nrows)]
cbax1 = plt.subplot(gs[1,1])
# First, plot lines w/ legend
a = ax[0]
a.set_title('Labeling with a legend')
for i in range(nlines):
a.plot(x, z[:,i], c=line_colors[i],lw=3,label='{:4.1f}'.format(y[i]))
leg = a.legend(loc='center left', bbox_to_anchor=(1, 0.5), ncol=2)
leg.set_title('Y')
# Next, plot with colorbar
a = ax[1]
a.set_title('Labeling with a "continuous" colorbar')
for i in range(nlines):
a.plot(x, z[:,i], c=line_colors[i],lw=3,label='{:3.1f}'.format(y[i]))
# Generate fake ScalarMappable for colorbar
sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=y[0],vmax=y[-1]))
sm.set_array([]) # You have to set a dummy-array for this to work...
cbar = plt.colorbar(sm, cax=cbax1)
cbar.set_label('Y')
cbar.set_ticks(y)
cbar.set_ticklabels(['{:4.1f}'.format(yi) for yi in y]) # Make 'em nicer-looking
# Moves colorbar closer to main axis by adjusting width-spacing between subplot axes.
fig.subplots_adjust(wspace=0.05, hspace=0.4)
# Set axis limits
for a in ax:
a.set_xlim(-np.pi, np.pi)
plt.savefig("./POP_LULC/example_colorbar.png")
当我把它保存为 .png 或 .pdf 格式时,图形显示不完整,颜色条(a)上的一些信息缺失,如下所示:
http://i5.tietuku.com/1701d9dcd4e5f24a.png
这就是我的问题,希望能得到你的指导!
在使用了
plt.tight_layout().
这是我的下一个示例:
在 Jupyter Notebook 中的截图:
http://i12.tietuku.com/f43490f03407695d.png保存的 png 图片:
http://i12.tietuku.com/f9faed607cac0a7a.png
即使我放大了 L/h,图形右侧的图例仍然显示不完整?
相关文章:
- 暂无相关问题
1 个回答
3
你需要在右边留出一些空间,以便放置两个列的图例。你可以使用你已经在代码里写的 subplots_adjust
来做到这一点。除了可以设置 hspace
(上下间距)和 wspace
(左右间距),subplots_adjust
还可以调整子图的位置和边距,使用的参数有 left
(左边距)、right
(右边距)、bottom
(下边距)和 top
(上边距)。
你只需要设置 right
这个参数。在这个例子中,我发现把它设置为 0.8
效果很好。
fig.subplots_adjust(wspace=0.05, hspace=0.4, right=0.8)