误差柱状图的python代码
时间: 2023-07-10 18:21:10 浏览: 41
下面是一个绘制预测误差柱状图的Python代码示例,其中使用了Matplotlib库来绘图:
```python
import numpy as np
import matplotlib.pyplot as plt
# 生成随机样本数据
y_true = np.random.rand(100)
y_pred = np.random.rand(100)
# 计算预测误差
errors = y_pred - y_true
# 对误差值进行排序,并获取排序后的样本索引
sorted_indexes = np.argsort(errors)
sorted_errors = errors[sorted_indexes]
sorted_indexes = sorted_indexes.tolist()
# 绘制误差柱状图
fig, ax = plt.subplots(figsize=(10, 6))
ax.bar(sorted_indexes, sorted_errors, color=np.where(sorted_errors < 0, 'r', 'g'))
# 添加水平线表示误差平均值
mean_error = np.mean(sorted_errors)
ax.axhline(mean_error, color='b', linestyle='--', label='mean error')
# 添加图例和标签
ax.legend()
ax.set_xlabel('Sample index')
ax.set_ylabel('Prediction error')
plt.show()
```
在这个示例代码中,首先生成了100个随机样本数据(真实值和预测值),然后计算了预测误差。接着,使用`argsort()`函数对误差值进行排序,并获取排序后的样本索引。最后,使用Matplotlib的`bar()`函数绘制误差柱状图,并使用`axhline()`函数添加一条水平线表示误差平均值。可以看到,使用这个代码可以方便地绘制预测误差柱状图,便于直观地观察预测结果和误差分布情况。