Skip to main content
 首页 » 编程设计

python之保存图形时颜色条无法完全显示

2024年10月24日1052php

以我从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时,图形不能完全显示,colorbar(a)部分信息缺失,如下:
http://i5.tietuku.com/1701d9dcd4e5f24a.png

这就是我的问题,希望您的指导!

使用后

    plt.tight_layout().         

这是我的下一个例子:

图右边的图例我把L/h放大也看不全?

请您参考如下方法:

您需要在右侧为两列图例留出一些空间。您可以使用 subplots_adjust 执行此操作调用你已经在那里了。除了设置 hspace 和 wspace,subplots_adjust 还可以使用 kwargs left 更改子图位置和边距>、右、底部 和顶部。

您只需要设置正确的参数。在这种情况下,我发现将其设置为 0.8 效果很好。

 fig.subplots_adjust(wspace=0.05, hspace=0.4, right=0.8)