简体   繁体   English

Matplotlib 曲线下区域条件颜色

[英]Matplotlib Area Under Curve conditional color

I'm trying to fill the area between two line plots as such:我正在尝试填充两个线图之间的区域,如下所示:

import matplotlib.pyplot as plt
import numpy as np


ROCE = np.array([-7.0,-14.0,-11.0,8.0,7.0,17.0,10.0,9.0])
WACC = np.array([4.5, 5.1, 4.7, 3.4, 2.9, 3.7, 3.6, 3.9])
YEAR = np.array([2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019])

fig, ax = plt.subplots(1,1)
ax.plot(YEAR, ROCE, color = 'blue')
ax.plot(YEAR, WACC, color = 'black')
ax.fill_between(YEAR, ROCE, WACC, where=ROCE >= WACC, facecolor='green')
ax.fill_between(YEAR, ROCE, WACC, where=ROCE <= WACC, facecolor='red')

I'm however having an issue at the point where the lines cross as can be seen in the attached image.但是,如附图中所示,我在线条交叉的地方遇到了问题。 I suspect I'll have to interpolate the line points.我怀疑我将不得不插入线点。 Any idea how one fixes this?知道如何解决这个问题吗?

Thanks!谢谢!

Plot Plot

Default, fill_between only looks at the given values.默认情况下, fill_between仅查看给定值。 But it also has an option to interpolate to find the exact crossing points for the where parameter.但它也有一个插值选项,以找到where参数的确切交叉点。

import matplotlib.pyplot as plt
import numpy as np

ROCE = np.array([-7.0,-14.0,-11.0,8.0,7.0,17.0,10.0,9.0])
WACC = np.array([4.5, 5.1, 4.7, 3.4, 2.9, 3.7, 3.6, 3.9])
YEAR = np.array([2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019])

fig, ax = plt.subplots(1,1)
ax.plot(YEAR, ROCE, color = 'blue')
ax.plot(YEAR, WACC, color = 'black')
ax.fill_between(YEAR, ROCE, WACC, where=ROCE >= WACC, interpolate=True, facecolor='green')
ax.fill_between(YEAR, ROCE, WACC, where=ROCE <= WACC, interpolate=True, facecolor='red')
plt.show()

结果图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM