如何在python中绘制实际值与预测值的关系图?

2024-09-30 14:37:27 发布

您现在位置:Python中文网/ 问答频道 /正文

          Original      Predicted
0           6            1.56
1           12.2         3.07
2           0.8          2.78
3           5.2          3.54
.                    

我尝试过的代码:

def plotGraph(y_test,y_pred,regressorName):
    if max(y_test) >= max(y_pred):
        my_range = int(max(y_test))
    else:
        my_range = int(max(y_pred))
    plt.scatter(y_test, y_pred, color='red')
    plt.plot(range(my_range), range(my_range), 'o')
    plt.title(regressorName)
    plt.show()
    return

我想要的图表: enter image description here

但我目前的产出是:

enter image description here


Tags: 代码testifmydefrangepltelse
3条回答

我不能模拟你的代码,但我第一眼看到了一些要点。首先,要规范化图形中的数据点。您需要将col中的所有数据点除以该col的最大值

您还应该检查文档中的“图例”功能,以添加所需图形的图例

在matplotlib(我假设您正在使用它)中documentation有一个matplotlib.pyplot.scatter函数的信息,前两个参数是:

x, y : float or array-like, shape (n, )
The data positions.

因此,对于您的应用程序,您需要在同一个图形上绘制两个散点图-使用matplotlib.pyplot.scatter两次。首先是y_test作为ycolor='red',其次是y_pred作为ycolor='blue'

不幸的是,您没有为y_test和y_pred提供x值的信息,但是您也需要这些信息来定义x函数调用中的plt.scatter

绘制两个散点图有点棘手,正如this answer所说,它需要对Axes对象的引用。例如(如答案所示):

import matplotlib.pyplot as plt

x = range(100)
y = range(100,200)
fig = plt.figure()
ax1 = fig.add_subplot(111)

ax1.scatter(x[:4], y[:4], s=10, c='b', marker="s", label='first')
ax1.scatter(x[40:],y[40:], s=10, c='r', marker="o", label='second')

有关更多详细信息,请查看matplotlib文档和提到的答案

您正在x轴上绘制y_测试,y轴上绘制y_pred。 你们想要的是x轴上的一个公共数据点,y轴上的y_test和y_pred。 下面的代码片段将帮助您实现这一点。 (其中,true_值和predicted_值是要打印的列表,common是数据帧中用作公共x轴的列表。)

    fig = plt.figure()
    a1 = fig.add_axes([0,0,1,1])
    x = common
    a1.plot(x,true_value, 'ro')
    a1.set_ylabel('Actual')
    a2 = a1.twinx()
    a2.plot(x, predicted_value,'o')
    a2.set_ylabel('Predicted')
    fig.legend(labels = ('Actual','Predicted'),loc='upper left')
    plt.show()

相关问题 更多 >