Á. Garzón
Á. Garzón

Reputation: 365

How to fill the two sides of a line with seaborn?

I need to fill with different colors (green and red maybe) the two sides of a graph. I'm using the following code:

import seaborn as sns
import matplotlib.pyplot as plt 
import matplotlib

range_x = [-1, 0, 1, 2]
range_y = [-5, -3, -1, 1]

ax = sns.lineplot(x = range_x, y = range_y, markers = True)
sns.lineplot(ax = ax, x = [range_x[0], range_x[-1]], y = [0, 0], color = 'black')
sns.lineplot(ax = ax, x = [0, 0], y = [range_y[0], range_y[-1]], color = 'black')

ax.fill_between(range_x, range_y, facecolor = 'red', alpha = 0.5)

plt.savefig('test_fig', bbox_inches = 'tight')
plt.close()

With that code I get the following figure:

enter image description here

But obviously this is a fail, because I want red color all above the blue line. Besides I want my x and y axis in a remarkable way, I get it with x axis but I don't know why I can't get it with y axis.

Thanks you very much in advance!

Upvotes: 0

Views: 2017

Answers (1)

CAPSLOCK
CAPSLOCK

Reputation: 6483

Something like this?:

ax = sns.lineplot(x = range_x, y = range_y, markers = True)
sns.lineplot(ax = ax, x = [range_x[0], range_x[-1]], y = [0, 0], color = 'black')
sns.lineplot(ax = ax, x = [0, 0], y = [range_y[0], range_y[-1]], color = 'black')

ax.fill_between(range_x, range_y,[ax.get_ylim()[1]]*len(range_x), facecolor = 'red', alpha = 0.5)
ax.fill_between(range_x, range_y,[ax.get_ylim()[0]]*len(range_x), facecolor = 'green', alpha = 0.5)

From the documentation of fill_between:

y2 : array (length N) or scalar, optional, default: 0 The y coordinates of the nodes defining the second curve.

Upvotes: 1

Related Questions