Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill area under curve in matlibplot python on log scale

I'm trying to fill the area under a curve with matplotlib. The script below works fine.

import matplotlib.pyplot as plt
from math import sqrt
x = range(100)
y = [sqrt(i) for i in x]
plt.plot(x,y,color='k',lw=2)
plt.fill_between(x,y,0,color='0.8')
plt.show()

However if I set the y-scale to logarithmic (see below). It sometimes fills the area above the curve ! Can anyone help me? I would like to fill the area between the curve and y = 0.

x = range(100)
y = [sqrt(i) for i in x]
plt.plot(x,y,color='k',lw=2)
plt.fill_between(x,y,0,color='0.8')
plt.yscale('log')
plt.show()

Thanks in advance!

like image 548
Loran de Vries Avatar asked Feb 28 '12 20:02

Loran de Vries


People also ask

How do you fill a curve under a area 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.

How do you change the log scale in Python?

pyplot library can be used to change the y-axis or x-axis scale to logarithmic respectively. The method yscale() or xscale() takes a single value as a parameter which is the type of conversion of the scale, to convert axes to logarithmic scale we pass the “log” keyword or the matplotlib. scale.

How do you fill between lines in Python?

You can easily fill in the area between values in a Matplotlib plot by using following functions: fill_between(): Fill the area between two horizontal curves. fill_betweenx(): Fill the area between two vertical curves.


1 Answers

With a logarithmic y-scale, fill_between(x, y, 0) tells matplotlib to fill the region between log(0) = -infinity and log(y). Naturally, it balks. You can avoid the problem by changing 0 to some small number like 1e-6.

like image 129
unutbu Avatar answered Sep 20 '22 14:09

unutbu