Python Pandas和matplotlib创建热图

Python Pandas和matplotlib创建热图,python,pandas,matplotlib,heatmap,Python,Pandas,Matplotlib,Heatmap,这是我使用anaconda、python3.5、pandas和matplotlib创建热图的代码。我使用的mac电脑有8GB的空间。输入数据采用excel格式,如下所示: Molecules cell line 1 cell line 2 cell line 3 cell line 4 cell line 5 cell line 6 cell line 7 cell line 8 cell line 10 cell line 11 cell line 12 cell lin

这是我使用anaconda、python3.5、pandas和matplotlib创建热图的代码。我使用的mac电脑有8GB的空间。输入数据采用excel格式,如下所示:

Molecules   cell line 1 cell line 2 cell line 3 cell line 4 cell line 5 cell line 6 cell line 7 cell line 8 cell line 10    cell line 11    cell line 12    cell line 13    cell line 14
molecule BRCA1  3   3   2   2   2   2   2   2   1   3   2   4   2
molecule BRCA2  2   4   1   1   1   1   1   1   1   1   2   1   2
molecule BRCA3  2   4   1   1   2   1   3   1   1   1   1   1   2
molecule BRCA4  2   4   1   1   1   1   2   1   1   1   1   1   2
molecule BRCA5  2   4   1   1   1   1   2   1   1   1   1   1   2
molecule BRCA6  2   4   1   1   1   1   2   1   1   1   1   1   2
.
.
.
代码Demo.py如下所示:

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import colors
import pandas as pd


Data = pd.read_excel("Demo.xlsx") #open excel file
data_value = Data.iloc[:,1:] # slice the data frame to remove first column
print(data_value) #print data frame


#high >2 fold = 1 = white = w
#low< 2 fold = 2 = green = g
#stable= 3 = blue = b
#unknown= 4 = red = r
cmapr = colors.ListedColormap(['w','g','b','r']) #set the color map to be used
cmap = plt.get_cmap(cmapr)


#create dendrograms
# -- include data frame
# -- include color map
# -- figure size IMP: Adjust as the data frame size
# -- remove the ticks from top left legend

cm = sns.clustermap(data_value,cmap = cmap, figsize=(100,120),cbar_kws={'format': '%s', 'ticks': []})

actual = Data.iloc[:,0]
final = []
lis = []
for t in cm.ax_heatmap.get_yticklabels():
    lis.append(str(t).split("'")[1])

for i in range(0,len(lis)):
    final.append(actual[int(lis[i])-1])
    print(actual[int(lis[i])-1])
#print(final)



# get the heat map to fix positions IMP: Adjust as the data frame output
hm = cm.ax_heatmap.get_position()

#fix the labels, adjust fontsize and rotation(read-ability)
plt.setp(cm.ax_heatmap.yaxis.get_majorticklabels(), fontsize=8, rotation = 0)
plt.setp(cm.ax_heatmap.xaxis.get_majorticklabels(), fontsize=15, rotation = 0)

#fix the heatmap size manually.
cm.ax_heatmap.set_position([hm.x0, hm.y0, hm.width*0.25, hm.height])

#get dendograph position and fix it(enlarge it)
# -- For column
col = cm.ax_col_dendrogram.get_position()
cm.ax_col_dendrogram.set_position([col.x0, col.y0, col.width*0.25, col.height*0.7]) #col.width*.25
# -- For row
row = cm.ax_row_dendrogram.get_position()
cm.ax_row_dendrogram.set_position([row.x0, row.y0, row.width*1.1, row.height]) #row.width*4

#set the label for xaxis
cm.ax_heatmap.set_xlabel("Cells",fontsize=15) 

#set the label for yaxis
cm.ax_heatmap.set_ylabel("Molecules",fontsize=15)
#cm.ax_heatmap.set_yticklabels(Data.iloc[:,0])
cm.ax_heatmap.set_yticklabels(final)

# -- dpi is for resolution
cm.savefig('Demo_final.pdf', dpi = 2000)


#cm.fig
将numpy导入为np
导入seaborn作为sns
将matplotlib.pyplot作为plt导入
从matplotlib导入颜色
作为pd进口熊猫
Data=pd.read_excel(“Demo.xlsx”)#打开excel文件
data_value=data.iloc[:,1:]#对数据帧进行切片以删除第一列
打印(数据_值)#打印数据框
#高>2倍=1=白色=w
#低<2倍=2=绿色=克
#稳定=3=蓝色=b
#未知=4=红色=r
cmapr=colors.ListedColormap(['w'、'g'、'b'、'r'])#设置要使用的颜色映射
cmap=plt.get\u cmap(cmapr)
#创建树状图
#--包含数据帧
#--包括彩色地图
#--图形大小IMP:根据数据帧大小进行调整
#--从左上角图例中删除记号
cm=sns.clustermap(数据值,cmap=cmap,figsize=(100120),cbar\u-kws={'format':'%s','ticks':[]})
实际值=数据.iloc[:,0]
最终=[]
lis=[]
对于厘米中的t.ax\u热图。获取\u yticklabels():
lis.append(str(t).split(“”)[1])
对于范围(0,len(lis))中的i:
final.append(实际[int(lis[i])-1])
打印(实际[int(lis[i])-1])
#打印(最终版)
#获取热图以固定位置IMP:调整为数据帧输出
hm=cm.ax\u热图。获取位置()
#固定标签,调整字体大小和旋转(阅读能力)
plt.setp(cm.ax\u heatmap.yaxis.get\u majorticklabels(),fontsize=8,rotation=0)
plt.setp(cm.ax_heatmap.xaxis.get_majorticklabels(),fontsize=15,rotation=0)
#手动修复热图大小。
厘米最大热图设置位置([hm.x0,hm.y0,hm.width*0.25,hm.height])
#获取dendograph位置并将其固定(放大)
#--对于列
col=cm.ax\u col\u树状图。获取位置()
cm.ax\u柱树状图设置位置([col.x0,col.y0,col.width*0.25,col.height*0.7])\col.width*.25
#--划船
row=cm.ax\u row\u树状图。获取位置()
cm.ax_行树状图。设置_位置([row.x0,row.y0,row.width*1.1,row.height])#行宽*4
#为xaxis设置标签
cm.ax\u热图集\u xlabel(“单元格”,fontsize=15)
#设置yaxis的标签
cm.ax\u热图。设置\u ylabel(“分子”,fontsize=15)
#cm.ax\u heatmap.set\u yticklabels(Data.iloc[:,0])
cm.ax\u热图。设置\u标签(最终)
#--新闻部是为了解决问题
cm.savefig('Demo_final.pdf',dpi=2000)
#无花果
输出如下:

Traceback (most recent call last):
  File "/Users/ww/PycharmProjects/Demo.py", line 65, in <module>
    final.append(actual[int(lis[i])-1])
  File "/Users/ww/anaconda/lib/python3.6/site-packages/pandas/core/series.py", line 601, in __getitem__
    result = self.index.get_value(self, key)
  File "/Users/ww/anaconda/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 2428, in get_value
    tz=getattr(series.dtype, 'tz', None))
  File "pandas/_libs/index.pyx", line 98, in pandas._libs.index.IndexEngine.get_value (pandas/_libs/index.c:4363)
  File "pandas/_libs/index.pyx", line 106, in pandas._libs.index.IndexEngine.get_value (pandas/_libs/index.c:4046)
  File "pandas/_libs/index.pyx", line 154, in pandas._libs.index.IndexEngine.get_loc (pandas/_libs/index.c:5085)
  File "pandas/_libs/hashtable_class_helper.pxi", line 756, in pandas._libs.hashtable.Int64HashTable.get_item (pandas/_libs/hashtable.c:13913)
  File "pandas/_libs/hashtable_class_helper.pxi", line 762, in pandas._libs.hashtable.Int64HashTable.get_item (pandas/_libs/hashtable.c:13857)
KeyError: -1

Process finished with exit code 1
回溯(最近一次呼叫最后一次):
文件“/Users/ww/PycharmProjects/Demo.py”,第65行,在
final.append(实际[int(lis[i])-1])
文件“/Users/ww/anaconda/lib/python3.6/site packages/pandas/core/series.py”,第601行,在__
结果=self.index.get_值(self,key)
文件“/Users/ww/anaconda/lib/python3.6/site packages/pandas/core/index/base.py”,第2428行,在get_值中
tz=getattr(series.dtype,'tz',无))
文件“pandas/_libs/index.pyx”,第98行,在pandas._libs.index.IndexEngine.get_值中(pandas/_libs/index.c:4363)
文件“pandas/_libs/index.pyx”,第106行,在pandas._libs.index.IndexEngine.get_值中(pandas/_libs/index.c:4046)
文件“pandas/_libs/index.pyx”,第154行,在pandas._libs.index.IndexEngine.get_loc中(pandas/_libs/index.c:5085)
文件“pandas/_libs/hashtable\u class\u helper.pxi”,第756行,在pandas.\u libs.hashtable.Int64HashTable.get\u项中(pandas/_libs/hashtable.c:13913)
文件“pandas/_libs/hashtable\u class\u helper.pxi”,第762行,在pandas.\u libs.hashtable.Int64HashTable.get\u项中(pandas/_libs/hashtable.c:13857)
键错误:-1
进程已完成,退出代码为1

请清楚地描述您期望的
最终。追加(实际[int(lis[i])-1])
操作。由于
actual
是一个数据帧,您可能需要以不同的方式访问其值;但是为了帮助您,您需要知道该代码行的用途。请清楚地描述您希望
final.append(实际[int(lis[i])-1])
做什么。由于
actual
是一个数据帧,您可能需要以不同的方式访问其值;但是为了帮助您,您需要知道该代码行的用途。