如何构建一个一个渐变颜色条图例(color bar)?

最近画图时采用默认的渐变色感觉很丑,就想着自己做一个,

用scatterplot 做图,默认渐变图例为圆点

# 导入模块
import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset("tips") # 导入数据
ax = sns.scatterplot(x="total_bill", y="tip", hue="size", data=tips) # 采用seaborn 中的scatterplot 画图,size 映射颜色大小,采用默认调色板。

在这里插入图片描述

图例为圆点,渐变色,想换成渐变条。

import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset("tips")
ax = sns.scatterplot(x="total_bill", y="tip", hue="size", palette='RdBu_r', data=tips)

# 画进度条
norm = plt.Normalize(tips['size'].min(), tips['size'].max()) # 取出渐变值的范围。
sm = plt.cm.ScalarMappable(cmap="RdBu_r", norm=norm) # 使用呢RdBu 色块映射数值,_r为颜色条的颜色反向
sm.set_array([])

# Remove the legend and add a colorbar
ax.get_legend().remove() # 将原来生成的圆点渐变图例删除。
ax.figure.colorbar(sm) # 加入图例

plt.show()

在这里插入图片描述
注意颜色条会占据figsize的范围,所以要画原来一样大小的图时,要把figsize调大一点。

猜你喜欢

转载自blog.csdn.net/weixin_44022515/article/details/114581673
bar