带有整套标签的Python图形

时间:2019-02-25 00:20:14

标签: python-3.x matplotlib

我正在尝试生成一个图以可视化整个协方差矩阵。  但是,我无法包含整个标签列表。请参见下面的工作示例:

import numpy as np

from matplotlib import pyplot as plt
from matplotlib import cm as cm

numberYears=len(range(2002,2018+1))
covMatrix=np.ones([numberYears,numberYears])
for count1,year1 in enumerate(range(2002,2018+1))    :
    for count2,year2 in enumerate(range(2002,2018+1))    :        
        covMatrix[count1,count2]=1-(abs(count1-count2)/numberYears)

fig = plt.figure()
ax1 = fig.add_subplot(111)
cmap = cm.get_cmap('rainbow', 30)
cax = ax1.imshow(covMatrix, interpolation="nearest", cmap=cmap)
labels=[]
for year in range(2002,2018+1):
    labels.append(str(year))

ax1.set_xticklabels(labels,fontsize=10,rotation=90)
ax1.set_yticklabels(labels,fontsize=10)   
fig.colorbar(cax, ticks=[.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0])
fig.savefig('map.png')

Representation of the covariance matrix

请注意,我的标签是[2002,2003,...,2017,2018],整个列表未包含在图中。我该如何处理?

1 个答案:

答案 0 :(得分:0)

考虑@ImportanceOfBeingErnest的评论,我找到了解决方案。我在函数“ imshow”中包括参数“ extent”,并且还包括“ set.xticks”:

from matplotlib import pyplot as plt
from matplotlib import cm as cm

numberYears=len(range(2002,2018+1))
covMatrix=np.ones([numberYears,numberYears])
for count1,year1 in enumerate(range(2002,2018+1))    :
    for count2,year2 in enumerate(range(2002,2018+1))    :        
        covMatrix[count1,count2]=1-(abs(count1-count2)/numberYears)

fig = plt.figure()
ax1 = fig.add_subplot(111)
cmap = cm.get_cmap('rainbow', 30)
cax = ax1.imshow(covMatrix, interpolation="nearest", cmap=cmap,extent=[2002,2018,2002,2018])
labels=[]
for year in range(2002,2018+1):
    labels.append(str(year))
ax1.set_xticks(listYears)
ax1.set_yticks(listYears)    

ax1.set_xticklabels(labels,fontsize=10,rotation=90)
ax1.set_yticklabels(labels,fontsize=10)   
fig.colorbar(cax, ticks=[.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0])
fig.savefig('mapTeste.png')