簡體   English   中英

使用Matplotlib繪制圓時出錯

[英]Error while plotting circles using matplotlib

我想使用python在隨機生成的點(在[0,1]之間)的數組的頂部繪制一個(半透明)圓。 我希望圓以(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'

我在這里想念什么? 任何幫助將不勝感激。

您需要在軸上繪制。

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()

輸出:

在此處輸入圖片說明

您需要從軸使用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()

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM