seaborn heatmap热力图用法 cbar水平横放 代码 python3

Install

sudo apt-get install python3-pandas
sudo apt-get install -y python3-seaborn
Note: Version command
  1. Dependencies
    Python 3.6+

  2. Mandatory dependencies
    numpy (>= 1.13.3)
    scipy (>= 1.0.1)
    pandas (>= 0.22.0)
    matplotlib (>= 2.1.2)



Use

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns

def plot_heatmap(robot_list, cp_list, mask = None):

	x_label = []
	for rob in range(0, 4):
		for i in range(1,8): 
			x_label.append(robot_list[rob]+'_'+str(i))

	f, ax= plt.subplots(figsize = (30, 8))
	plt.subplots_adjust(left=0.05, right=0.95, top=0.98, bottom=0.05)
	
	if mask is None:
		ax = sns.heatmap(cp_list, annot=True, fmt='.3g', linewidths=.01,
						annot_kws={'size':15}, yticklabels=robot_list, xticklabels=x_label,
						cmap="YlGnBu", ax=ax, cbar=True, 				 
						square=False)
	else:
		with sns.axes_style("white"):
			cbar_ax = f.add_axes([.65, .83, .3, .06])
			ax = sns.heatmap(cp_list, annot=True, fmt='.3g', linewidths=.01, mask=mask,
						annot_kws={'size':15}, yticklabels=robot_list, xticklabels=x_label,
						cmap="YlGnBu", ax=ax, cbar_ax=cbar_ax, cbar=True, 
						cbar_kws={"orientation":"horizontal","shrink":1}, 
						square=False)

	# color: https://matplotlib.org/users/colormaps.html

	# title
	ax.set_title('Comparsion among four Franka robots', fontsize=24, position=(0.5, 1))
	plt.subplots_adjust(top=0.92)

	ax.set_xlabel('Joint of four robots',fontsize=20)
	ax.set_ylabel('Robots',fontsize=20)

	# matplotlib.axes.Axes.tick_params
	# ax.tick_params(axis='y',labelsize=15) # y axis
	# ax.tick_params(axis='x',labelsize=15) #, colors='b', labeltop=True, labelbottom=False) # x axis

	# use matplotlib.colorbar.Colorbar object
	cbar = ax.collections[0].colorbar
	cbar.ax.tick_params(labelsize=15)

	# put the xaxis tick on the top
	# ax.xaxis.tick_top()
	# ax.tick_params(axis='x',labelsize=6, colors='b', labeltop=True, labelbottom=False) 

	# rotate the ticklabel, set the fontsize 
	ax.set_xticklabels(ax.get_xticklabels(), rotation=35, fontsize=15)
	ax.set_yticklabels(ax.get_yticklabels(), fontsize=15)

	f.savefig('compare_rect.png', dpi=100, bbox_inches='tight')

if __name__ == "__main__":
	# print "dataset:"
	robot_list = ['purple','blue', 'red', 'orange' ]
	sampling_rate = 500

	###### run the comparsion for each two robots ######
	# run_compare(robot_list, sampling_rate)

	# load the dataset
	cp_list = np.load("cp_list.npy")
	mask = np.load("cp_list_mask.npy")

	###### plot heatmap #######
	plot_heatmap(robot_list, cp_list)

	plt.show()



Figure

  • with mask (triangle)

Note that the position of colorbar

  • without mask (rectangle)

在这里插入图片描述


References

Colors

cmap: Python基于seaborn绘制喜欢的热力图,不同色系一览

Another good tutorial for multiple subfigures

Ref:Matplotlib中多子图绘图时,坐标轴及其label的几种排布方式

fig, axes = plt.subplots(3, 3, sharex=True, sharey=True, figsize=(6,5))
fig.subplots_adjust(wspace = .1,hspace = 0)

for i, row in enumerate(axes):
    for j, col in enumerate(row):
        im = col.imshow(np.arange(100).reshape((10,10)))
#         ax_cb = fig.colorbar(im, ax=col)
        if col.is_last_row():
            col.set_xlabel('x')
        if col.is_first_col():
            col.set_ylabel('y')
        col.set_xticks(np.arange(0, 11, 2))
        col.set_yticks(np.arange(0, 11, 2))
        col.set_xticklabels(np.arange(1, 11, 2))
        col.set_yticklabels(np.arange(1, 11, 2))
            
fig.subplots_adjust(bottom=0, right=0.9, top=1)
cax = plt.axes([0.92, 0.03, 0.03, 0.95])
cb = fig.colorbar(im, cax=cax)
cb.ax.tick_params()
cb.set_label('colorbar')

# plt.tight_layout() # 使用 tight layout 需要手动调整 colorbar 位置,否则会很难看
plt.show()

在这里插入图片描述

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python 中,使用 seaborn 库的 heatmap() 函数可以绘制热力图,以可视化数据的相关性。 热力图的颜色表示变量之间的相关性,通常使用颜色映射(colormap)来表示。常用的颜色映射有: - Sequential(顺序):从浅色到深色表示逐渐增加的数值。 - Diverging(分散):从浅色到深色,中间的颜色表示平均值,分别表示低于平均值和高于平均值的数值。 - Categorical(类别):为每个类别分配不同的颜色。 除了颜色映射,热力图还可以添加注释(注释数值)、设置颜色条(colorbar)和调整图像大小等。 下面是一个示例代码: ```python import seaborn as sns import pandas as pd # 读取数据 data = pd.read_csv('data.csv') # 计算相关系数矩阵 corr = data.corr() # 绘制热力图 sns.heatmap(corr, cmap='coolwarm', annot=True, cbar=True, square=True, fmt='.2f', annot_kws={'size': 10}) # 设置图像属性 sns.set(font_scale=1.5) sns.set_style('whitegrid') plt.title('Correlation Heatmap') # 显示图像 plt.show() ``` 在这个示例代码中,首先读取数据,并计算相关系数矩阵。然后,使用 heatmap() 函数绘制热力图,设置参数 cmap='coolwarm' 来指定颜色映射,参数 annot=True 来显示注释,参数 cbar=True 来显示颜色条,参数 square=True 来将图形设置为正方形,参数 fmt='.2f' 来设置注释格式为小数点后两位,参数 annot_kws={'size': 10} 来设置注释字体大小为 10。 接着,设置图像属性,使用 sns.set() 函数来设置字体大小,使用 sns.set_style() 函数来设置网格线样式,使用 plt.title() 函数来设置标题。 最后,使用 plt.show() 函数显示图像。 通过观察热力图,可以看出数据中各个变量之间的相关性,可以发现一些有趣的数据模式和趋势,以便进一步分析和解释数据。同时,热力图也可以帮助我们选择变量,以便进行后续的建模和预测。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值