开拓者期货期权程序化系统交易论坛

标题: 【Python】相关系数矩阵的可视化作图 [打印本页]

作者: yebenli    时间: 2015-6-25 13:11:24     标题: 【Python】相关系数矩阵的可视化作图

本帖最后由 yebenli 于 2015-6-25 16:38 编辑
  1. #import matplotlib.cm
  2. import matplotlib.colors as col
  3. import matplotlib.pyplot as plt
  4. import numpy as np
  5.    
  6. class DrawPcolor(object):
  7.     def __init__(self):
  8.         ##self define the colorbar
  9.         startcolor = '#006400'  # a dark green
  10.         midcolor = '#ffffff'    # a bright white
  11.         endcolor = '#ee0000'    # a dark red
  12.         self.Mycmap = col.LinearSegmentedColormap.from_list('MyColorbar',[startcolor,midcolor,endcolor])#use the "fromList() method

  13.     def Pcolor(self,*args,**kwargs):
  14.         #*args is a tuple,**kwargs is a dict;
  15.         #Here args means the Matrix Corr,kwargs includes the key of the " AddText function"
  16.         self.fig=plt.figure()
  17.         self.ax = self.fig.add_subplot(111)   
  18.         self.Data=args[0];
  19.         heatmap = self.ax.pcolor(self.Data,cmap=self.Mycmap);#cmap=plt.cm.Reds)
  20.         self.fig.colorbar(heatmap)
  21.         # want a more natural, table-like display
  22.         self.ax.invert_yaxis()
  23.         self.ax.xaxis.tick_top()
  24.         self.ax.set_xticks(np.arange(self.Data.shape[0]) + 0.5, minor=False)
  25.         self.ax.set_yticks(np.arange(self.Data.shape[1]) + 0.5, minor=False)
  26.         
  27.         if kwargs['AddText']==True:
  28.             for y in range(self.Data.shape[1]):
  29.                 for x in range(self.Data.shape[0]):
  30.                     self.ax.text(x + 0.5, y + 0.5, '%.2f' % self.Data[y, x],
  31.                              horizontalalignment='center',
  32.                              verticalalignment='center',
  33.                              )
  34.         self.fig.show()

  35.     def Set_labelticks(self,*tick_labels):
  36.         # put the major ticks at the middle of each cell
  37.         self.ax.set_xticklabels(tick_labels[0],rotation=0, minor=False)
  38.         self.ax.set_yticklabels(tick_labels[1],rotation=0, minor=False )
  39.         self.fig.show()

  40. def Main():
  41.     data = np.random.rand(5, 4)
  42.     Corr = np.corrcoef(data)
  43.     xlabel_ticks=["a",'b','c','d','e']#range(Corr.shape[0]);#
  44.     ylabel_ticks=["A","B","C",'D','E']#range(Corr.shape[1]);#
  45.     MyPict=DrawPcolor()
  46.     MyPict.Pcolor(Corr,3,4,4,AddText=True,b=1) # params 3,4,4,b has no effect on the exec
  47.     MyPict.Set_labelticks(xlabel_ticks,ylabel_ticks)

  48. if __name__=='__main__':
  49.     Main()

  50.         
  51.         
复制代码
[attach]31885[/attach]




欢迎光临 开拓者期货期权程序化系统交易论坛 (http://bbs.tb18.net/) Powered by Discuz! X2