Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling region between curve and x-axis in Python using Matplotlib

I am trying to simply fill the area under the curve of a plot in Python using MatPlotLib.

Here is my SSCCE:

import json
import pprint
import numpy as np
import matplotlib.pyplot as plt

y = [0,0,0,0,0,0,0,0,0,0,0,863,969,978,957,764,767,1009,1895,980,791]
x = np.arange(len(y))


fig2, ax2 = plt.subplots()
ax2.fill(x, y)

plt.savefig('picForWeb.png')
plt.show()

The attached picture shows the output produced.output of fill

Does anyone know why Python is not filling the entire area in between the x-axis and the curve?

I've done Google and StackOverflow searches, but could not find a similar example. Intuitively it seems that it should fill the entire area under the curve.

like image 437
user2826735 Avatar asked Nov 23 '13 17:11

user2826735


3 Answers

I usually use the fill_between function for these kinds of plots. Try something like this instead:

import numpy as np
import matplotlib.pyplot as plt

y = [0,0,0,0,0,0,0,0,0,0,0,863,969,978,957,764,767,1009,1895,980,791]
x = np.arange(len(y))

fig, (ax1) = plt.subplots(1,1); 
ax1.fill_between(x, 0, y)
plt.show()

See more examples here.

like image 76
Trond Kristiansen Avatar answered Oct 03 '22 04:10

Trond Kristiansen


If you want to use this on a pd.DataFrame use this:

df.abs().interpolate().plot.area(grid=1, linewidth=0.5)

interpolate() is optional.

enter image description here

like image 29
Artur Müller Romanov Avatar answered Oct 03 '22 05:10

Artur Müller Romanov


plt.fill assumes that you have a closed shape to fill - interestingly if you add a final 0 to your data you get a much more sensible looking plot.

import numpy as np
import matplotlib.pyplot as plt

y = [0,0,0,0,0,0,0,0,0,0,0,863,969,978,957,764,767,1009,1895,980,791,0]
x = np.arange(len(y))


fig2, ax2 = plt.subplots()
ax2.fill(x, y)

plt.savefig('picForWeb.png')
plt.show()

Results in: Closed Plot

Hope this helps to explain your odd plot.

like image 37
Steve Barnes Avatar answered Oct 03 '22 05:10

Steve Barnes