【问题标题】:How to fill the two sides of a line with seaborn?如何用seaborn填充一条线的两侧?
【发布时间】:2019-05-13 16:34:47
【问题描述】:

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

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.7 seaborn


    【解决方案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,[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_betweendocumentation

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多