Skip to main content
 首页 » 编程设计

Python,如何填充不共享横坐标的多条曲线

2025年02月15日7lonelyxmas

我试图填充 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() 

这是绘制时它们的样子:

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

请您参考如下方法:

您需要在包含所有数组中的所有 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)