plot circle on unequal axes with pyplot

前端 未结 3 397
一个人的身影
一个人的身影 2021-01-11 17:17

I would like to plot a circle on an auto-scaled pyplot-generated graphic. When I run

ax.get_aspect()

hoping for a value with which I could

3条回答
  •  孤城傲影
    2021-01-11 18:08

    It really does depend what you want it for.

    The problem with defining a circle in data coordinates when aspect ratio is auto, is that you will be able to resize the figure (or its window), and the data scales will stretch nicely. Unfortunately, this would also mean that your circle is no longer a circle, but an ellipse.

    There are several ways of addressing this. Firstly, and most simply, you could fix your aspect ratio and then put a circle on the plot in data coordinates:

    import matplotlib.pyplot as plt
    import numpy as np
    
    
    fig = plt.figure()
    ax = plt.axes()
    
    ax.set_aspect(1)
    theta = np.linspace(-np.pi, np.pi, 200)
    plt.plot(np.sin(theta), np.cos(theta))
    
    plt.show()
    

    data coords circle

    With this, you will be able to zoom and pan around as per usual, but the shape will always be a circle.

    If you just want to put a circle on a figure, independent of the data coordinates, such that panning and zooming of an axes did not effect the position and zoom on the circle, then you could do something like:

    import matplotlib.patches as mpatches
    import matplotlib.pyplot as plt
    import numpy as np
    
    
    fig = plt.figure()
    ax = plt.axes()
    patch = mpatches.Circle((325, 245), 180, alpha=0.5, transform=None)
    fig.artists.append(patch)
    
    
    plt.show()
    

    device coordinates circle

    This is fairly advanced mpl, but even so, I think it is fairly readable.

    HTH,

提交回复
热议问题