Matplotlib:cbar.set_xticklabels没有效果

时间:2016-04-06 08:13:42

标签: python matplotlib

我已经将一年365天分配给了几个群集,我现在正试图将它们绘制在热图上。

我的代码工作正常,但cbar.set_ticks(some_range)没有效果:我的颜色条上的刻度标签有正确的文字,但位置错误a colorbar with wrong yticks

这是一个MCVE

from datetime import date
import numpy as np
import pandas as pd
import matplotlib.pylab as plt
import matplotlib
import seaborn as sns

#create some random data
n_cluster = 4
index = pd.date_range('01/01/2016', end='31/12/2016', freq='1D')
df = pd.DataFrame(np.random.randint(0, n_cluster, len(index)), 
             index=index, columns=['cluster'])

pivot = df.pivot_table('cluster', 
    columns=[lambda x: x.weekofyear], 
    index= [lambda x: x.dayofweek])

#yticklabels of the heatmap
days =  [date(2018, 1, d).strftime('%a')[:3] for d in range(1, 8)]

#get a discrete cmap
cmap = plt.cm.get_cmap('RdBu', n_cluster)

fig = plt.figure(figsize=(10,3))
gs = matplotlib.gridspec.GridSpec(1, 2, width_ratios=[50,1])
ax = plt.subplot(gs[0])
cbar = plt.subplot(gs[1])
sns.heatmap(pivot, square=True, cmap=cmap,
            yticklabels=days, ax=ax, cbar_ax=cbar)

#There is something wrong here
cbar.set_yticks([i + 1/(2.0*n_cluster) for i in np.arange(0, 1, 1.0/n_cluster)])

#This one is ok
cbar.set_yticklabels(range(0, n_cluster))

感谢您的帮助

1 个答案:

答案 0 :(得分:3)

作为解决方法,以下内容在正确的位置添加正确的标签

cbar.yaxis.set_ticks([0.125, 0.375, 0.625, 0.875])

看起来像, enter image description here

编辑: 或者是mfitzp的更一般的建议,

cbar.yaxis.set_ticks([i + 1/(2.0*n_cluster) 
                      for i in np.arange(0, 1, 1.0/n_cluster)])