Search code examples
pythonmatplotlibplotellipse

Can't plot ellipse without fillcolor


I really can't get this and I need to superimpose an ellipse onto an image. The problem is plotting the ellipse with the matplotlib.patches, but ending up with either a white graph or a filled ellipse. The code is very primitive and I'm not sure what to do, since I've never worked with this part of the matplotlib library.

import matplotlib.pyplot as plt
import numpy.random as rnd
from matplotlib.patches import Ellipse


ells = [Ellipse(xy=[0,0], width=30, height=10, angle=0,edgecolor='b', lw=4)]

fig = plt.figure(0)
ax = fig.add_subplot(111, aspect='equal')
for e in ells:
    ax.add_artist(e)
    e.set_alpha(1)
    e.set_facecolor(none) #obvious mistake, but no idea what to do

ax.set_xlim(-100, 100)
ax.set_ylim(-100, 100)

plt.show()

I tried looking up the matplotlib.patches page, but there is no clear info on how to plot an ellipse, just the function in use.


Solution

  • In general, to specify no color for an argument in matplotlib, use the string 'none'. This applies equally for edge colors, face colors, etc.

    In your case:

    import matplotlib.pyplot as plt
    from matplotlib.patches import Ellipse
    
    fig, ax = plt.subplots()
    
    ax.axis('equal')
    ell = Ellipse(xy=[0,0], width=30, height=10, angle=0,
                  edgecolor='b', lw=4, facecolor='none')
    
    ax.add_artist(ell)
    ax.set(xlim=[-100, 100], ylim=[-100, 100])
    
    plt.show()
    

    enter image description here

    For fill specifically, you can also use fill=False, as @M4rtini notes in the comments. In matplotlib, using the set(foo=bar) or set_foo(bar) methods are typically identical to passing in the kwarg foo=bar. For example:

    import matplotlib.pyplot as plt
    from matplotlib.patches import Ellipse
    
    fig, ax = plt.subplots()
    
    ax.axis('equal')
    ell = Ellipse(xy=[0,0], width=30, height=10, angle=0,
                  edgecolor='b', lw=4, fill=False)
    
    ax.add_artist(ell)
    ax.set(xlim=[-100, 100], ylim=[-100, 100])
    
    plt.show()