본문 바로가기
파이썬

파이썬 Matplotlib plot numpy matrix as 0 index

by º기록 2020. 12. 25.
반응형

numpy 행렬을 준비한 다음 matplotlib를 사용하여 다음과 같이 행렬을 플로팅합니다.

>>> import numpy
>>> import matplotlib.pylab as plt
>>> m = [[0.0, 1.47, 2.43, 3.44, 1.08, 2.83, 1.08, 2.13, 2.11, 3.7], [1.47, 0.0, 1.5,     2.39, 2.11, 2.4, 2.11, 1.1, 1.1, 3.21], [2.43, 1.5, 0.0, 1.22, 2.69, 1.33, 3.39, 2.15, 2.12, 1.87], [3.44, 2.39, 1.22, 0.0, 3.45, 2.22, 4.34, 2.54, 3.04, 2.28], [1.08, 2.11, 2.69, 3.45, 0.0, 3.13, 1.76, 2.46, 3.02, 3.85], [2.83, 2.4, 1.33, 2.22, 3.13, 0.0, 3.83, 3.32, 2.73, 0.95], [1.08, 2.11, 3.39, 4.34, 1.76, 3.83, 0.0, 2.47, 2.44, 4.74], [2.13, 1.1, 2.15, 2.54, 2.46, 3.32, 2.47, 0.0, 1.78, 4.01], [2.11, 1.1, 2.12, 3.04, 3.02, 2.73, 2.44, 1.78, 0.0, 3.57], [3.7, 3.21, 1.87, 2.28, 3.85, 0.95, 4.74, 4.01, 3.57, 0.0]]
>>> matrix = numpy.matrix(m)
>>> matrix
matrix([
    [ 0.  ,  1.47,  2.43,  3.44,  1.08,  2.83,  1.08,  2.13,  2.11, 3.7 ],
    [ 1.47,  0.  ,  1.5 ,  2.39,  2.11,  2.4 ,  2.11,  1.1 ,  1.1 , 3.21],
    [ 2.43,  1.5 ,  0.  ,  1.22,  2.69,  1.33,  3.39,  2.15,  2.12, 1.87],
    [ 3.44,  2.39,  1.22,  0.  ,  3.45,  2.22,  4.34,  2.54,  3.04, 2.28],
    [ 1.08,  2.11,  2.69,  3.45,  0.  ,  3.13,  1.76,  2.46,  3.02, 3.85],
    [ 2.83,  2.4 ,  1.33,  2.22,  3.13,  0.  ,  3.83,  3.32,  2.73, 0.95],
    [ 1.08,  2.11,  3.39,  4.34,  1.76,  3.83,  0.  ,  2.47,  2.44, 4.74],
    [ 2.13,  1.1 ,  2.15,  2.54,  2.46,  3.32,  2.47,  0.  ,  1.78, 4.01],
    [ 2.11,  1.1 ,  2.12,  3.04,  3.02,  2.73,  2.44,  1.78,  0.  , 3.57],
    [ 3.7 ,  3.21,  1.87,  2.28,  3.85,  0.95,  4.74,  4.01,  3.57, 0.  ]
])
>>> fig = plt.figure()
>>> ax = fig.add_subplot(1,1,1)
>>> ax.set_aspect('equal')
>>> plt.imshow(matrix, interpolation='nearest', cmap=plt.cm.ocean)
>>> plt.colorbar()
>>> plt.show()

플롯은 다음과 같이 표시됩니다.

여기에 이미지 설명 입력

내 축이 0-9가 아닌 1-10에서 이동하기를 원한다는 사실을 제외하고는 괜찮습니다 (파이썬의 0 인덱싱에서 파생 됨)

이 작업을 수행하는 간단한 방법이 있습니까?

감사합니다 !!

 

해결 방법

 


#All the stuff earlier in the program
plt.imshow(matrix, interpolation='nearest', cmap=plt.cm.ocean, extent=(0.5,10.5,0.5,10.5))
plt.colorbar()
plt.show()

임의의 모양을 가진 행렬의 경우이 코드를 다음과 같이 변경할 수 있습니다.

#All the stuff earlier in the program
plt.imshow(matrix, interpolation='nearest', cmap=plt.cm.ocean,
    extent=(0.5,numpy.shape(matrix)[0]+0.5,0.5,numpy.shape(matrix)[1]+0.5))
plt.colorbar()
plt.show()

이렇게하면 다음과 같은 플롯이 생성됩니다.

플롯 출력

 

참조 페이지 https://stackoverflow.com/questions/21071128

 

 

반응형

댓글