作者:ahworld
鏈接:python畫(huà)圖自定義colorbar
來(lái)源:微信公眾號(hào)-seqyuan
著作權(quán)歸作者所有捺宗,任何形式的轉(zhuǎn)載都請(qǐng)聯(lián)系作者。
自定義colorbar包含兩方面:
- 自定義colorbar的顏色組合及顏色占比
- 自定義colorbar的位置和大小
這兩項(xiàng)比較簡(jiǎn)單和實(shí)用析校,matplotlib和seaborn都可以嘗試。對(duì)于某些特殊的數(shù)據(jù)分布類型薛闪,想在一張圖內(nèi)顯示的情況比較適合鲜屏。
cmap的自定義
cmap本質(zhì)是一個(gè)RGBA格式的顏色列表肉盹,元素類型為np.array() 昔驱,np.array()里包含4個(gè)0-1的元素,前3個(gè)是RGB值上忍,第4個(gè)為透明度骤肛。
seaborn取顏色列表可以用以下方式:
- sns.light_palette('blue',reverse=True,n_colors=5)
- plt.cm.get_cmap('Blues', 5)
- plt.cm.get_cmap('cubehelix', 5)
如果數(shù)據(jù)中有兩組相差比較大的數(shù)據(jù)構(gòu)成,可考慮取兩組顏色值合并窍蓝,可通過(guò)n_colors
參數(shù)控制兩組顏色的占比腋颠,如果存在極值,極值可設(shè)置為特殊顏色吓笙。
colorbar的位置和大小
可以把colorbar作為單獨(dú)的axes淑玫,自由地定義其位置和占圖比例,例如colorbar可以這樣設(shè)置:cbar_ax = fig.add_axes([0.7, 0.75, 0.025, 0.2])
面睛,在seaborn熱圖中有對(duì)應(yīng)的參數(shù)接受自定義的colorbar絮蒿。
#!/usr/bin/env python
# coding: utf-8 -*-
import pandas as pd
import numpy as np
## 以下為MACOS設(shè)置,linux請(qǐng)改為 ?matplotlib.use('Agg')
matplotlib.use('TkAgg')
## juypter notebook顯示圖像設(shè)置
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
cmap= sns.light_palette('blue',reverse=True,n_colors=5)
cmap2=sns.light_palette('red',reverse=False,n_colors=15)
cmap.extend(cmap2)
cmap.append(np.array([.3,.7,.6,1]))
cmap.insert(0,np.array([.7,.7,.5,1]))
fig = plt.figure(figsize=(4,7))
ax = fig.add_axes([0.38, 0.3, 0.3, 0.65], facecolor = 'white')
cbar_ax = fig.add_axes([0.7, 0.75, 0.025, 0.2])
df = pd.DataFrame(np.random.rand(12,5))
ax = sns.heatmap(df, ax=ax,annot=False, cmap=cmap, linewidths=.5, cbar_ax = cbar_ax)
下圖的效果對(duì)比更明顯