matplotlib如何保存单独的colorbar

今天给大家介绍下matplotlib如何保存单独的colorbar。

示例如下:

python 复制代码
import matplotlib.pyplot as plt   
import numpy as np  
from scipy.io import savemat,loadmat
from PIL import Image
# 示例数据  
data = np.random.rand(100, 100) 
  
# 创建图形和轴
fig, ax = plt.subplots() 
  
# 在轴上绘制图像  
im = ax.imshow(data, cmap='viridis')  
# ax.set_axis_off()
# plt.savefig('image.png', bbox_inches='tight', pad_inches=0) # bbox_inches='tight' 会尝试裁剪图像到内容的最小矩形区域,而 pad_inches=0 则确保没有额外的填充。)
# image = Image.open('image.png')
# # 注意:Pillow的resize方法接受一个元组,表示新的尺寸(宽度,高度)  
# resized_image = image.resize(data.shape)  
# # 保存调整大小后的图片
# resized_image.save('resized_image.png')  

"""新建一个图层,用于绘制颜色条"""
fig2, ax2 = plt.subplots() 
ax2.set_axis_off()
# 添加colorbar  
cbar = fig2.colorbar(im, ax=ax2)  
#  cbar.set_ticks(ticks=cticks)
  
# 去掉colorbar的边框(即Axes的边框)  
cbar.ax.tick_params(which='both', size=0)  # 去掉刻度线  
cbar.outline.set_visible(False)  # 如果直接可用,但通常不起作用,因为colorbar没有直接的outline属性 

# 注意:Matplotlib的较新版本中,可能需要通过修改patches来去掉边框  
# 但这通常不是必要的,因为上面的tick_params已经足够了  
# 如果需要完全移除任何可能的边框痕迹,可以尝试以下(但通常不需要)  
# for spine in cbar.ax.spines.values():  
#     spine.set_visible(False) 

保存colorbar的三种方式:

第一种方式:使用subplots_adjust调整子图

python 复制代码
fig2.subplots_adjust(left=0.8, bottom=0, right=1, top=1)  # colorbar会自适应缩小,不美观
plt.savefig('cbar.png', bbox_inches='tight', pad_inches=0) 

第二种方式:使用 get_window_extent() 获取当前颜色条的窗口,但其只保留颜色条,不保存标签之类的

python 复制代码
fig2.subplots_adjust(left=0.8, bottom=0, right=1, top=1) 
plt.savefig('cbar2.png', bbox_inches=cbar.ax.get_window_extent().transformed(fig2.dpi_scale_trans.inverted()), pad_inches=0) 

第三种方式:使用 get_tightbbox() 获取当前颜色条,保留颜色条以及标签之类的

python 复制代码
plt.savefig('cbar3.png', bbox_inches=cbar.ax.get_tightbbox(fig2.canvas.get_renderer()).transformed(fig2.dpi_scale_trans.inverted()), pad_inches=0) 

最终结果展示:

python 复制代码
# 关闭图形
plt.close(fig)
plt.close(fig2)

# 显示图形  
plt.subplot(1,3,1)
plt.imshow(plt.imread('cbar.png'))
plt.axis('off')
plt.subplot(1,3,2)
plt.imshow(plt.imread('cbar2.png'))
plt.axis('off')
plt.subplot(1,3,3)
plt.imshow(plt.imread('cbar3.png'))
plt.axis('off')
plt.savefig('cbar4.png')
相关推荐
muddjsv2 天前
Matplotlib 饼图与环形图:占比类数据可视化方法
信息可视化·matplotlib
如果曾经拥有4 天前
matplotlib - 绘制ROC曲线95%置信区间
matplotlib
muddjsv4 天前
了解Matplotlib 核心基础:环境配置 + 三层架构 + 绘图流程
matplotlib
醉舞经阁半卷书15 天前
Matplotlib从入门到精通
python·数据分析·matplotlib
葱明撅腚6 天前
seaborn绘图(下)
python·matplotlib·可视化·seaborn·图表绘制
_Soy_Milk7 天前
【算法工程师】—— Python 数据分析
python·数据分析·numpy·pandas·matplotlib
智航GIS18 天前
11.2 Matplotlib 数据可视化教程
python·信息可视化·matplotlib
weixin_4657909121 天前
热电联产系统智能经济调度:深度强化学习的奇妙应用
matplotlib
爱喝可乐的老王24 天前
数据分析实践--数据解析购房关键
信息可视化·数据分析·pandas·matplotlib