Python matlibplot: визуализация матрицы целых чисел (-1, 0 или 1) с кружками (одинакового радиуса, другого цвета) - PullRequest
0 голосов
/ 07 мая 2019

У меня квадратная матрица, заполненная -1, 0 или 1. Я хотел бы визуализировать эту матрицу со сферами или кругами одинакового радиуса. Радиус, действительно, вообще не важен. Тем не менее, эти круги должны иметь другой цвет в зависимости от номера ячейки матрицы.

Например: Матрица 10 x 10 -> 100 кругов на плоскости, 10 строк по 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 голосов
/ 07 мая 2019

Вы можете непосредственно использовать разброс следующим образом:

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

0 голосов
/ 07 мая 2019

Вот код matplotlib, который использует матрицу рассеяния :

# 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
)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...