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')
相关推荐
爱喝可乐的老王4 天前
数据分析实践--数据解析购房关键
信息可视化·数据分析·pandas·matplotlib
海棠AI实验室5 天前
第 十五 章 可视化入门:Matplotlib 做出像样的图
matplotlib
渡我白衣10 天前
计算机组成原理(11):加法器
python·机器学习·numpy·pandas·matplotlib·计组·数电
老歌老听老掉牙11 天前
使用 Matplotlib 自定义坐标轴字体及刻度样式详解
python·matplotlib
AC赳赳老秦12 天前
DeepSeek教育科技应用:智能生成个性化学习规划与知识点拆解教程
前端·网络·数据库·人工智能·学习·matplotlib·deepseek
AC赳赳老秦14 天前
行业数据 benchmark 对比:DeepSeek上传数据生成竞品差距分析报告
开发语言·网络·人工智能·python·matplotlib·涛思数据·deepseek
2401_8414956415 天前
【Python高级编程】图着色动态可视化 APP
python·算法·matplotlib·tkinter·回溯法·图着色算法·动态可视化工具
laocooon52385788615 天前
对传入的 x , y 两个数组做折线图, x 对应 x 轴, y 对应 y 轴。并保存到 Task1/image1/T2.png
python·numpy·pandas·matplotlib
渡我白衣16 天前
Python 与数据科学工具链入门:NumPy、Pandas、Matplotlib 快速上手
人工智能·python·机器学习·自然语言处理·numpy·pandas·matplotlib