代码之家  ›  专栏  ›  技术社区  ›  Commoner

使用matplotlib绘制圆时出错

  •  1
  • Commoner  · 技术社区  · 7 年前

    我想在随机生成的点(介于 [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 ,我得到正常输出(没有所需的圆)。但是当我在代码中包括引用 圆环1 ,我得到以下错误输出。

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

    我这里缺什么?任何帮助都将不胜感激。

    2 回复  |  直到 7 年前
        1
  •  1
  •   Scott Boston    7 年前

    您需要使用“从轴添加艺术家”,以下是获取当前轴的最快方法 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

        2
  •  1
  •   harvpan    7 年前

    你需要在坐标轴上绘图。

    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