如何在python中绘制实际值与预测值的关系图?
我尝试过的代码:如何在python中绘制实际值与预测值的关系图?,python,pandas,dataframe,matplotlib,Python,Pandas,Dataframe,Matplotlib,我尝试过的代码: Original Predicted 0 6 1.56 1 12.2 3.07 2 0.8 2.78 3 5.2 3.54 . 我想要的图表: 但我目前的产出是: 我无法模拟您的代码,但我第一眼看到了一些要点。首先,要规范化图形中的数据点。您需要将col
Original Predicted
0 6 1.56
1 12.2 3.07
2 0.8 2.78
3 5.2 3.54
.
我想要的图表:
但我目前的产出是:
我无法模拟您的代码,但我第一眼看到了一些要点。首先,要规范化图形中的数据点。您需要将col中的所有数据点除以该col的最大值 您还应该检查文档中的图例函数,以添加所需图形的图例。在matplotlib(我假设您正在使用它的代码)中有一个关于
matplotlib.pyplot.scatter
函数的信息,前两个参数是:
x,y:浮点数或类似数组的形状(n,)数据位置 因此,对于您的应用程序,您需要在同一个图形上绘制两个散点图-使用
matplotlib.pyplot.scatter
两次。首先使用y\u测试asy
和color='red'
,其次使用y\u pred
asy
和color='blue'
不幸的是,您没有为y_test和y_pred提供x值的信息,但是您也需要这些信息来定义plt.scatter
函数调用中的x
绘制两个散点图有点棘手,正如所说的,它需要一个对轴的引用。例如(如答案所示):
查看matplotlib文档和提到的答案以了解更多详细信息。您似乎遇到的问题是将y\u test
和y\u pred
混合到一个“绘图”中(这里指scatter()
函数)
使用scatter()
或plot()
函数(您也将其混淆),第一个参数是x轴上的坐标,第二个参数是y轴上的坐标
因此1.)您需要一个只使用y\u测试的scatter()
,然后一个只使用y\u pred
。要做到这一点,您需要有2D数据,或者像您的情况一样,只需使用range()
功能为x轴使用索引即可
下面是一些包含随机数据的代码,可能会帮助您开始:
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')
这将为您提供如下信息:
您正在绘制x轴上的y_测试和y轴上的y_pred。
你们想要的是x轴上的一个公共数据点,y轴上的y_test和y_pred。
下面的代码片段将帮助您实现这一点。
(其中,true_值和predicted_值是要打印的列表,common是数据帧中用作公共x轴的列表。)
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')
import matplotlib.pyplot as plt
import numpy as np
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(range(len(y_test)), y_test, color='blue')
plt.scatter(range(len(y_pred)), y_pred, color='red')
plt.title(regressorName)
plt.show()
return
y_test = range(10)
y_pred = np.random.randint(0, 10, 10)
plotGraph(y_test, y_pred, "test")
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()