首页 > 解决方案 > 如何用seaborn填充一条线的两侧?

问题描述

我需要在图表的两侧填充不同的颜色(可能是绿色和红色)。我正在使用以下代码:

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()

使用该代码,我得到下图:

在此处输入图像描述

但显然这是失败的,因为我想要蓝色线以上的红色。除了我想要我的 x 和 y 轴以一种非凡的方式,我用 x 轴得到它,但我不知道为什么我不能用 y 轴得到它。

非常感谢您提前!

标签: python-2.7seaborn

解决方案


像这样的东西?:

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)

从以下文档fill_between

y2 : 数组(长度 N)或标量,可选,默认值:0 定义第二条曲线的节点的 y 坐标。


推荐阅读