【问题标题】:Fill area between a curve and diagonal lines填充曲线和对角线之间的区域
【发布时间】:2021-11-26 09:00:11
【问题描述】:

你能帮我解决这个问题吗? 我想知道如何填充曲线和对角线(连接 (X min, Y min) 到 (X max, Y max) 的线)之间的区域。例如,在下面的图中,我们如何填充上面的区域对角线为红色,下方区域为蓝色。提前请您花时间考虑。

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize = (6,4))
x=np.array([0,1,2,3,4,5,6,7,8,9,10])
y=np.array([0,4,5,5,4,5,6,8,9,9,15])

ax.plot(x,y, color = "red", lw=1.2)
ax.plot([x.min(),x.max()],[y.min(),y.max()], color = "black", lw=1.2)

plt.show()

【问题讨论】:

标签: python pandas numpy matplotlib seaborn


【解决方案1】:

谢谢你。我能做到这一点。我用 [x.min(),x.max()],[y.min(),y.max()] 拟合了一个线性回归模型来定义对角线,然后用对角线。

import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize = (6,4))
x=np.array([0,1,2,3,4,5,6,7,8,9,10])
y=np.array([0,4,5,5,4,5,6,8,9,9,15])

ax.plot(x,y, color = "red", lw=1.2)
(m,b)=np.polyfit([x.min(),x.max()] ,[y.min(),y.max()] ,1)
yp = np.polyval([m,b],x)
plt.plot(x,yp, color='black',lw=1)
ax.fill_between(x,y, yp, where=(y > yp), color='red',interpolate=True)
ax.fill_between(x, y, yp, where=(y <= yp), color='blue',interpolate=True)
plt.show()

【讨论】:

    【解决方案2】:

    fill_between() 方法是专门为此设计的:

    # Create empty figure 
    _,ax = plt.subplots()
    # Plot the two lines
    ax.plot(x,x,color='C0')
    ax.plot(x,y,color='C3')
    # Plot the area with two conditions (x>y) and (x<=y)
    ax.fill_between(x, x, y, where=(x > y), color='C0', alpha=0.2,
                     interpolate=True)
    ax.fill_between(x, x, y, where=(x <= y), color='C3', alpha=0.2,
                     interpolate=True)
    

    我们得到:

    【讨论】:

    • Obchadron,感谢您的回答。抱歉,因为我最初认为我没有很好地解释我的问题。当我说对角线时,我指的是连接 (X min, Y min) 到 (X max Y max) 的线,它可以是 ax.plot([x.min(),x.max()],[y .min(),y.max()], color = "black", lw=1.2).
    猜你喜欢
    • 2016-01-14
    • 2019-04-19
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    • 1970-01-01
    • 2013-11-23
    相关资源
    最近更新 更多