Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill an area within a polygon in Python using matplotlib?

Here is a code I tried:

from scipy.spatial import ConvexHull
points = np.random.rand(30, 2)   # 30 random points in 2-D
hull = ConvexHull(points)

import matplotlib.pyplot as plt
%matplotlib inline
corners=[]
for simplex in hull.simplices:
    corners+=list(simplex)
plt.fill(points[corners, 0], points[corners, 1], 'k',alpha=0.3)

The only plot I can get is: Convex Hull of random set of points in matplotlib As you can see it is filled partly.

But I'd like all the area within this polygon should be filled.

What are the ways of doing it?

I appreciate any your advice!

Upd: An Answer!!!

Actually I've just found an answer. It was on the official site of SciPy:

We could also have directly used the vertices of the hull, which for 2-D are guaranteed to be in counterclockwise order

So to do what I want I just needed to use:

plt.fill(points[hull.vertices,0], points[hull.vertices,1], 'k', alpha=0.3)

instead of last 4 lines of my upper code.

May be this question/answer will help anyone else.

like image 261
Nataly Avatar asked Mar 27 '16 18:03

Nataly


People also ask

How do I fill an area in Matplotlib?

fill_between() is used to fill area between two horizontal curves. Two points (x, y1) and (x, y2) define the curves. this creates one or more polygons describing the filled areas.

How do I shade part of a graph in Matplotlib?

Plot x and y data points, with color=red and linewidth=2. To shade an area parallel to X-axis, initialize two variables, y1 and y2. To add horizontal span across the axes, use axhspan() method with y1, y2, green as shade color,and alpha for transprency of the shade. To display the figure, use show() method.

How do you fill under a graph in Python?

To fill the area under the curve, put x and y with ste="pre", using fill_between() method. Plot (x, y1) and (x, y2) lines using plot() method with drawstyle="steps" method. To display the figure, use show() method.


1 Answers

Actually I've just found an answer. It was on the official site of SciPy:

We could also have directly used the vertices of the hull, which for 2-D are guaranteed to be in counterclockwise order So to do what I want I just needed to use:

plt.fill(points[hull.vertices,0], points[hull.vertices,1], 'k', alpha=0.3)

instead of last 4 lines of my upper code.

May be this question/answer will help anyone else.

like image 145
Nataly Avatar answered Sep 22 '22 03:09

Nataly