首页 > 解决方案 > 如何自定义 matplotlib 中的误差线

问题描述

我打算在我的图中绘制所有可能的信息,包括平均值、标准差和 MSE,并参考图中的每个点。

from sklearn.metrics import mean_absolute_error as mae
from sklearn.metrics import mean_squared_error as mse
import numpy as np
import matplotlib.pyplot as plt

为了简单起见,假设我只有三点。

true = np.array([[1047.]
 [ 953.]
 [1073.]])
pred = np.array([[ -69.921265]
 [-907.8611  ]
 [ 208.98877 ]])

my_mae= mae(true, pred) #mean absolute error
my_mse= mse(true,pred) #mean squared error

err = abs(true - pred) #get the error per point
mean_err = np.mean(err) #calculate the mean
sd_err  = np.std(err) #calculate the standard deviation

然后,我绘制我的错误栏。

dy= 100

plt.errorbar(true,pred, yerr=dy, fmt='o', color='black',ecolor='red', elinewidth=3, capsize=0);

首先,我想以某种方式引用每个错误栏以查看它引用的数据点。其次,我想将所有四条信息添加到情节中。我会很感激任何帮助。

在此处输入图像描述

标签: pythonnumpymatplotlibplot

解决方案


在这里,如果这解决了您的问题,请考虑接受答案:

from sklearn.metrics import mean_absolute_error as mae
from sklearn.metrics import mean_squared_error as mse
import numpy as np
import matplotlib.pyplot as plt

true = np.array([[1047.],
 [ 953.],
 [1073.]])
pred = np.array([[ -69.921265],
 [-907.8611  ],
 [ 208.98877 ]])

my_mae= mae(true, pred) #mean absolute error
my_mse= mse(true,pred) #mean squared error

err = abs(true - pred) #get the error per point
mean_err = np.mean(err) #calculate the mean
sd_err  = np.std(err) #calculate the standard deviation

dy= 100

for i, z in enumerate (pred,1):
    plt.errorbar(true,pred, yerr=dy, fmt='o', color='black',ecolor='red', elinewidth=3, capsize=0, zorder=3);
    plt.annotate(i, (true[i-1], pred[i-1]),fontsize=20, color='blue')
    
label_1=['my_mae','my_mse', 'mean_err', 'sd_err']
label_2=[my_mae,my_mse, mean_err,sd_err]

for q,w in zip(label_1, label_2): 
    plt.plot([], [],'o', label=(f'{q}: {w}'))

plt.legend(loc='lower right')

这是你应该得到的:

在此处输入图像描述


推荐阅读