Ошибка при построении кругов с помощью matplotlib - PullRequest
0 голосов
/ 23 мая 2018

Я хочу нарисовать (полупрозрачный) круг поверх массива случайно сгенерированных точек (между [0,1]), используя python.Я хочу, чтобы круг центрировался на (0.5, 0.5)

Это код, который я написал:

import numpy as np
import matplotlib.pyplot as plt 

x_gal = np.random.rand(20)
y_gal = np.random.rand(20)

x_rand = np.random.rand(5*20) 
y_rand = np.random.rand(5*20)

plt.figure(1)
plt.plot( x_gal, y_gal, ls=' ', marker='o', markersize=5, color='r' )
plt.plot( 0.5, 0.5, ls=' ', marker='o', markersize=5, color='r' )
plt.plot( x_rand, y_rand, ls=' ', marker='o', markersize=5, color='b' )
plt.axis('off')

circle1 = plt.Circle((0.5, 0.5), 0.2, color='r', alpha=0.5)
plt.add_artist(circle1)

plt.tight_layout()
plt.show()

Без строк в коде, которые относятся к circle1, я получаюнормальный вывод (без нужного круга).Но когда я включаю в код строки, которые относятся к circle1, я получаю следующее сообщение об ошибке:

AttributeError: 'module' object has no attribute 'add_artist'

Что мне здесь не хватает?Любая помощь будет принята с благодарностью.

Ответы [ 2 ]

0 голосов
/ 23 мая 2018

Вам нужно использовать add_artist от осей, ниже приведен самый быстрый способ получить текущие оси, используя plt.gcf, получить текущую фигуру и get_gca, получить текущие оси, также я рекомендую plt.axis('equal') нарисовать кругпротив овала:

import numpy as np
import matplotlib.pyplot as plt 
import matplotlib as mpl

x_gal = np.random.rand(20)
y_gal = np.random.rand(20)

x_rand = np.random.rand(5*20) 
y_rand = np.random.rand(5*20)

plt.figure(1)
plt.plot( x_gal, y_gal, ls=' ', marker='o', markersize=5, color='r' )
plt.plot( 0.5, 0.5, ls=' ', marker='o', markersize=5, color='r' )
plt.plot( x_rand, y_rand, ls=' ', marker='o', markersize=5, color='b' )
plt.axis('off')
plt.axis('equal')

circle1 = plt.Circle((0.5, 0.5), 0.2, color='r', alpha=0.5)
plt.gcf().gca().add_artist(circle1)

plt.tight_layout()
plt.show()

enter image description here

0 голосов
/ 23 мая 2018

Вам нужно построить на оси.

import numpy as np
import matplotlib.pyplot as plt 

x_gal = np.random.rand(20)
y_gal = np.random.rand(20)

x_rand = np.random.rand(5*20) 
y_rand = np.random.rand(5*20)

fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot( x_gal, y_gal, ls=' ', marker='o', markersize=5, color='r' )
ax.plot( 0.5, 0.5, ls=' ', marker='o', markersize=5, color='r' )
ax.plot( x_rand, y_rand, ls=' ', marker='o', markersize=5, color='b' )
ax.axis('off')

circle1 = plt.Circle((0.5, 0.5), 0.2, color='r', alpha=0.5)
ax.add_artist(circle1)

plt.tight_layout()
plt.show()

Выход:

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...