Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shade the area between two axhline using matplotlib

What I'm trying to achieve: a plot with two axhline horizontal lines, with the area between them shaded.

The best so far:

    ax.hline(y1, color=c)
    ax.hline(y2, color=c)
    ax.fill_between(ax.get_xlim(), y1, y2, color=c, alpha=0.5)

The problem is that this leaves a small amount of blank space to the left and right of the shaded area.

I understand that this is likely due to the plot creating a margin around the used/data area of the plot. So, how do I get the fill_between to actually cover the entire plot without matplotlib rescaling the x-axis after drawing? Is there an alternative to get_xlim that would give me appropriate limits of the plot, or an alternative to fill_between?

This is the current result:

The current result

Note that this is part of a larger grid layout with several plots, but they all leave a similar margin around these shaded areas.

like image 943
Grismar Avatar asked Nov 30 '17 07:11

Grismar


People also ask

How do you fill an area between two lines in python?

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. The 'where' parameter can be used to selectively fill some areas.

Which command in Matplotlib is used to color between to plot in PLT plot?

colors() This function is used to specify the color.


2 Answers

Not strictly speaking an answer to the question of getting the outer limits, but it does solve the problem. Instead of using fill_between, I should have used:

    ax.axhspan(y1, y2, facecolor=c, alpha=0.5)

Result:

enter image description here

like image 127
Grismar Avatar answered Sep 18 '22 22:09

Grismar


ax.get_xlim() does return the limits of the axis, not that of the data:

Axes.get_xlim()

Returns the current x-axis limits as the tuple (left, right).

But Matplotlib simply rescales the x-axis after drawing the fill_between:

import matplotlib.pylab as pl
import numpy as np

pl.figure()
ax=pl.subplot(111)
pl.plot(np.random.random(10))

print(ax.get_xlim())

pl.fill_between(ax.get_xlim(), 0.5, 1)

print(ax.get_xlim())

This results in:

(-0.45000000000000001, 9.4499999999999993)

(-0.94499999999999995, 9.9449999999999985)

If you don't want to manually set the x-limits, you could use something like:

import matplotlib.pylab as pl
import numpy as np

pl.figure()
ax=pl.subplot(111)
pl.plot(np.random.random(10))

xlim = ax.get_xlim()

pl.fill_between(xlim, 0.5, 1)

ax.set_xlim(xlim)
like image 21
Bart Avatar answered Sep 18 '22 22:09

Bart