Search code examples
pythonmatplotlibpolygon

Making a polygon with Python matplotlib


I tried to make a single polygon with the following code, but it made two?

import matplotlib.pyplot as plt

x = [4, 1, 2]
y = [1, 2, 1]
z = [0, 2, 1]

plt.fill(x, y, z)
plt.show()

This code displays two polygons in different colors, but I want one polygon with a single, unified color.


Solution

  • Just set the color of the polygons to be the same:

    import matplotlib.pyplot as plt
    
    x = [4, 1, 2]
    y = [1, 2, 1]
    z = [0, 2, 1]
    
    plt.fill(x, y, z, c='C0')
    plt.show()
    

    Filled polygon

    I'm not completely certain why the preceding code works like it does. plt.fill() is used for plotting 2D polygons, and the third argument should be the color, so what you should really write is this:

    x = [4, 1, 0, 2]
    y = [1, 2, 0, 1]
    
    plt.fill(x, y, c='C0')
    plt.show()
    

    (which gives the same plot)

    Filled polygon