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')
相关推荐
恣艺17 小时前
解决 PyCharm 2024.1+ matplotlib 图表显示异常:Plots 工具窗口空白 / tostring_rgb 报错
ide·pycharm·matplotlib
是上好佳佳佳呀2 天前
【数据分析|Day02】Matplotlib 数据可视化笔记
笔记·matplotlib
ice8130331812 天前
【Python】Matplotlib折线图绘制
开发语言·python·matplotlib
北暮城南4 天前
使用 Claude Code 高效实现图像边缘检测:多算法对比与工程实践
python·opencv·numpy·matplotlib·边缘检测·claude code
red2brick6 天前
【使用PyQt6与Matplotlib编写交互式生成一元二次函数图形程序】
matplotlib
DogDaoDao9 天前
OpenCV 踩坑全指南
图像处理·人工智能·python·opencv·计算机视觉·matplotlib·rgb
电魂泡哥9 天前
Matplotlib.pyplot 完全入门指南
信息可视化·matplotlib
十年之少10 天前
matplotlib 与 PyQt5 结合使用——PyQt5
matplotlib·pyqt5
河阿里11 天前
Python数据可视化:Matplotlib从入门到精通
python·信息可视化·matplotlib
songyuc13 天前
Matplotlib&seaborn学习笔记
笔记·学习·matplotlib