以我从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笔记本中的屏幕切换 http://i12.tietuku.com/f43490f03407695d.png
图中右侧的图例即使放大了L / h也无法完全显示?
答案 0 :(得分:2)
您需要在右侧为两列图例创建一些空间。您可以通过此处已有的subplots_adjust
来拨打电话。除了设置hspace
和wspace
之外,subplots_adjust
还可以使用kwargs left
,right
,{{1}更改子图位置和边距}和bottom
。
您只需设置top
参数即可。在这种情况下,我发现将其设置为right
效果很好。
0.8