Python Matlibplot:用圆(相同的半径,不同的颜色)可视化整数(-1、0或1)矩阵

时间:2019-05-07 13:41:50

标签: python matplotlib

我有一个用-1、0或1填充的正方形矩阵。我想用相同半径的球或圆将这个矩阵可视化。半径确实根本不重要。但是,这些圆圈必须根据矩阵像元的数量具有不同的颜色。

例如: 10 x 10矩阵->平面上100个圆,10行x 10列 位置(2,9)的圆形颜色取决于位置(2,9)的矩阵数量。

谢谢!

我认识的人告诉我使用matlibplot,但是我对Python和 我有很多问题!

这是我到目前为止所做的: {`

import numpy as np
#from implementations import *
#from config import *
import matplotlib.pyplot as plt

A = np.array([
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 1, 2, -1, -1,-1, 2, 1, 0, 0],
    [0, 1, 2, -1, -1,-1, 2, 1, 0, 0],
    [0, 1, 2, -1, -1,-1, 2, 1, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
])

rows=len(A) # finding number rows of lattice, so no need to worry about it!
columns=len(A[0]) # finding number columns of lattice, so no need to worry about it!

fig, ax = plt.subplots()

for i in range(rows):
      for j in range(columns):
          if A[i][j]==-1:
              circle1 = plt.Circle((i*4, j*4), 2, color='blue')
              fig = plt.gcf()
              ax = fig.gca()
              ax.add_artist(circle1)
          if A[i][j]== 1:
              circle2 = plt.Circle((i*4, j*4), 2, color='yellow')
              fig = plt.gcf()
              ax = fig.gca()
              ax.add_artist(circle2)
      `}

2 个答案:

答案 0 :(得分:0)

以下是使用scatter matrixmatplotlib代码:

# Imports
import matplotlib.pyplot as plt
from itertools import chain

# Create plot
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

# Here is our matrix. Note, that it is expected to be rectangular!
matrix = [
    [0, 1, 0,1],
    [-1,1, 0,0],
    [1,-1,-1,1],
]

# Get X-length
X = len(matrix[0])

# Get Y-length
Y = len(matrix)

# Construct grids for scatter
x_grid = list(range(X)) * Y  # 1,2,3,4,1,2,3,4...
y_grid = [y for y in range(Y) for _ in range(X)]  # 1,1,1,1,2,2,2,2...

# Flatten the matrix because ax.scatter uses flat arrays
matrix_grid = list(chain(*matrix))

plt.scatter(
    x_grid,              # X-grid array of coordinates
    y_grid,              # Y-grid array of coordinates
    c=matrix_grid,       # Our flatten matrix of -1/0/1s
    cmap='gist_rainbow'  # Color map - defines colors
)

答案 1 :(得分:0)

您可以直接使用散点图,如下所示:

import numpy as np
import matplotlib.pyplot as plt

A = np.array([
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 1, 2, -1, -1,-1, 2, 1, 0, 0],
    [0, 1, 2, -1, -1,-1, 2, 1, 0, 0],
    [0, 1, 2, -1, -1,-1, 2, 1, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
])

X,Y = np.meshgrid(np.arange(A.shape[1]), np.arange(A.shape[0]))
plt.scatter(X.flatten(), Y.flatten(), c=A.flatten())

plt.show()

enter image description here