【问题标题】:Python, How to fill multiple curves that do not share abscissa coordinates?Python,如何填充不共享横坐标的多条曲线?
【发布时间】:2017-08-19 09:40:25
【问题描述】:

我正在尝试填充 4 条曲线的顶部轮廓和底部轮廓之间的区域,最终目的是计算该填充区域的面积。问题是曲线不共享 x 坐标,因此fill_between() 的使用并不简单。

这是一个起点:

import matplotlib.pyplot as plt
from sklearn.metrics import auc
import json
import numpy as np

x1 = [0,   0.1, 0.2, 0.6, 0.7, 0.75, 1]
y1 = [0.5, 0.6, 0.7, 0.8, 1,   1,    1]

x2 = [0,   0.01, 0.2, 0.4, 0.7, 0.75,  1]
y2 = [0.6, 0.5,  0.8, 0.7, 0.9, 1,     1]

x3 = [0,   0.2, 0.45, 0.5,  0.6, 0.9, 1]
y3 = [0.4, 0.5, 0.55, 0.8, 0.9, 0.9, 1]

plt.xlim([-0.01, 1.01])
plt.ylim([-0.01, 1.01])

auc1 = auc(x1, y1)
plt.plot(x1,y1 ,'r', label='(AUC = %.2f)' % auc1)

auc2 = auc(x2, y2)
plt.plot(x2,y2, 'b', label='(AUC = %.2f)' % auc2)

auc3 = auc(x3, y3)
plt.plot(x3,y3, 'g', label='(AUC = %.2f)' % auc3)

plt.legend(loc='lower right')
plt.show()

这是绘制时的样子:

如果需要,我会使用另一种编程语言。如果确切地知道我想要实现的目标会使问题更容易回答,我可以添加更多细节。

【问题讨论】:

    标签: python matplotlib area roc auc


    【解决方案1】:

    您需要在包含所有数组的所有 x 值的新 x 数组上插入 y 值。为此,您可以使用numpy.interp

    import matplotlib.pyplot as plt
    import numpy as np
    
    x1 = [0,   0.1, 0.2, 0.6, 0.7, 0.75, 1]
    y1 = [0.5, 0.6, 0.7, 0.8, 1,   1,    1]
    
    x2 = [0,   0.01, 0.2, 0.4, 0.7, 0.75,  1]
    y2 = [0.6, 0.5,  0.8, 0.7, 0.9, 1,     1]
    
    x3 = [0,   0.2, 0.45, 0.5,  0.6, 0.9, 1]
    y3 = [0.4, 0.5, 0.55, 0.8, 0.9, 0.9, 1]
    
    # create array of all unique x values
    x_all = x1 + x2 + x3
    x_all = np.unique(np.array(x_all))
    
    # interpolate y values on new xarray
    y_all = np.empty((len(x_all), 3))
    for i,x,y in zip(range(3), [x1,x2,x3], [y1,y2,y3]):
        y_all[:,i] = np.interp(x_all, x, y)
    
    # find out min and max values    
    ymin = y_all.min(axis=1)
    ymax = y_all.max(axis=1)
    
    
    plt.fill_between(x_all, ymin, ymax, alpha=0.6)
    
    plt.plot(x1,y1 ,'r', label='(AUC = %.2f)')
    plt.plot(x2,y2, 'b', label='(AUC = %.2f)')
    plt.plot(x3,y3, 'g', label='(AUC = %.2f)')
    plt.ylim(0,1.1)
    plt.legend(loc='lower right')
    plt.show()
    

    当然你也可以在更密集的网格上进行插值,

    x_all = np.linspace(0,1,101)
    

    【讨论】:

    • 嗨@ImportanceOfBeingErnest,您的代码在Xs 和Ys 上运行得非常好。我尝试使用我的真实数据集,但它没有填充曲线之间。我认为存在浮点问题。有什么方法可以把我的真实 X1,Y1,X2,Y2 发给你,让你看看吗?请
    猜你喜欢
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 2018-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多