我正在努力创建一个相关矩阵。创建矩阵工作正常,直到我尝试添加颜色条。
这是我目前的代码:
def corr_matrix(data):
'''function to find the mean for days'''
data=data.ix[:,1:].corr(method='pearson')
row_lab=[]
col_lab=[]
for i in data:
row_lab.append(i)
col_lab.append(i)
column_labels = col_lab
row_labels = row_lab
data=np.round(data.corr(method='pearson').abs(), decimals=2)
data=np.array(data)
fig, ax = plt.subplots()
plt.axis('tight')
heatmap = ax.pcolor(data, cmap='RdPu'),
plt.colorbar(mappable=heatmap) # put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[0])+0.5, minor=False)
ax.set_yticks(np.arange(data.shape[1])+0.5, minor=False)
ax.invert_yaxis()
ax.xaxis.tick_top()
ax.set_xticklabels(row_labels, minor=False, rotation=90)
ax.set_yticklabels(column_labels, minor=False)
plt.show()
我试过了plt.colorbar()
。这也不起作用。任何帮助都会很棒!!
我看过这个问题:AttributeError while adding colorbar in matplotlib但答案似乎不起作用:(
这是我的错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\AClayton\WinPython-64bit-2.7.5.3\python-2.7.5.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 538, in runfile
execfile(filename, namespace)
File "C:/Users/AClayton/Desktop/HData/correlation.py", line 152, in <module>
cmat=corr_matrix(all_data)
File "C:/Users/AClayton/Desktop/HData/correlation.py", line 88, in corr_matrix
plt.colorbar(mappable=heatmap) # put the major ticks at the middle of each cell
File "C:\Users\AClayton\WinPython-64bit-2.7.5.3\python-2.7.5.amd64\lib\site-packages\matplotlib\pyplot.py", line 2121, in colorbar
ret = gcf().colorbar(mappable, cax = cax, ax=ax, **kw)
File "C:\Users\AClayton\WinPython-64bit-2.7.5.3\python-2.7.5.amd64\lib\site-packages\matplotlib\figure.py", line 1451, in colorbar
cb = cbar.colorbar_factory(cax, mappable, **kw)
File "C:\Users\AClayton\WinPython-64bit-2.7.5.3\python-2.7.5.amd64\lib\site-packages\matplotlib\colorbar.py", line 1274, in colorbar_factory
cb = Colorbar(cax, mappable, **kwargs)
File "C:\Users\AClayton\WinPython-64bit-2.7.5.3\python-2.7.5.amd64\lib\site-packages\matplotlib\colorbar.py", line 852, in __init__
mappable.autoscale_None()
AttributeError: 'tuple' object has no attribute 'autoscale_None'
EDIIT
all_data
替换为数据,因为这是一个错字。
data=pd.DataFrame(np.random.rand(10,10))
产生错误
答案 0 :(得分:3)
这是一个我并不自豪的答案,你可能会对你的问题有同感 我走了:
错误
AttributeError: 'tuple' object has no attribute 'autoscale_None'
触发
mappable.autoscale_None()
在
中告诉你热图plt.colorbar(mappable=heatmap)
实际上是一个元组
怎么来的?
如果你写
>>> a = 1,
你正在定义一个元组
>>> a
(1,)
>>> type(a)
<type 'tuple'>
这与你在:
中所做的相同heatmap = ax.pcolor(data, cmap='RdPu'),
所以,摆脱分号,你会得到一个像这样的好身材: