# What's the issue with my code for visualizing linear regression in 3 dimensions with matplotlib? [closed]

I am trying to use linear regression that takes two variables "Idade" and "LF" and tries to predict a third one, "DGAF". I'm trying to both do the scatterplot with the observations and the model prediction on the same graph. Bellow is the code I used (using Python).

X = df[["Idade","LF"]]
y = df["DGAF"].values.reshape(len(df["DGAF"]),1)

reg = LinearRegression()
reg.fit(X, y)

fig = plt.figure()
ax = Axes3D(fig)

x_pred = np.linspace(0,100,1000)
y_pred = np.linspace(0,100,1000)
xx_pred, yy_pred = np.meshgrid(x_pred, y_pred)

model_viz = np.array([xx_pred.flatten(), yy_pred.flatten()]).T

ax.set_xlabel('Years since oil change')
ax.set_ylabel('LF')
ax.set_zlabel('DGA Score')

ax.plot(model_viz[0], model_viz[1], reg.predict(model_viz),color='red')
plt.show()


I get this error:

ValueError: input operand has more dimensions than allowed by the axis remapping


I am able to do the scatterplot, the issue seems to be with plotting the prediction. How can I solve this?

• Why are you using ax.plot instead of ax.scatter as your did in the first part or ax.plot_surface to plot the surface ? these should work with your input arguments. – Ubikuity May 10 at 19:15
• @Ubikuity, thank you for your suggestion. After trying to use scatter I found out that there were some issues with the matrix transposition as well – J. Dionisio May 10 at 21:45
• Perfect, glad that one worked out. Was not sure at all about these 3D plots since I rarely use them, in spite of how badass they are. – Ubikuity May 10 at 22:37

Following the suggestion given by @Ubikuity, I changed the ax.plot to ax.scatter, but there were still some issues with the dimensions. It was due to the transposition of the matrices, that was being done in the wrong place. The code below works correctly.

X = df[["Idade","LF"]]
y = df["DGAF"].values.reshape(len(df["DGAF"]),1)

reg = LinearRegression()
reg.fit(X, y)

fig = plt.figure()
ax = Axes3D(fig)

x_pred = np.linspace(0,100,100)
y_pred = np.linspace(0,100,100)
xx_pred, yy_pred = np.meshgrid(x_pred, y_pred)

model_viz = np.array([xx_pred.flatten(), yy_pred.flatten()])

ax.set_xlabel('Years since oil change')
ax.set_ylabel('LF')
ax.set_zlabel('DGA Score')

ax.scatter(model_viz[0], model_viz[1], reg.predict(model_viz.T),color='red')
plt.show()
$$$$
`