Python Forum
Issue with plotting (basic)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Issue with plotting (basic)
#1
I am supposed to plot angle = (slope)*voltage + (intercept) using linear regression
and angle and voltage are given.
angle (radians) = [-1.57, -1.26, -0.94, -0.63, -0.31, 0., 0.31, 0.65, 0.96, 1.23, 1.52]

voltage (volts) = [1.176, 1.648, 1.874, 2.175, 2.438, 2.503, 2.925, 3.067, 3.450, 3.686, 4.014]

I need to find slope, r^2 and interscept and plot this.

this is my code.

import numpy as np
import matplotlib.pyplot as plt
import csv
import pandas as pd
from sklearn.linear_model import LinearRegression 

#%%-------------------------------------
#number 1

voltage= np.array([1.176,1.648,1.874,2.175,2.438,2.503,2.925,3.067,3.450,3.686,4.014]).reshape(1,-1)
angle  = np.array([-1.57,-1.26,-0.94,-0.63,-0.31,0.,0.31,0.65,0.96,1.23,1.52]).reshape(1,-1)


# Linear Regression
model    = LinearRegression().fit(voltage, angle.reshape(1,-1))
Rsquared = model.score(angle, voltage)
slope, intercept = model.coef_, model.intercept_
print('intercept =', intercept)
print('slope =', slope)
print('coefficient of determination =', Rsquared)


# Plot the raw data and regression using a scatter plot
plt.figure(1)
plt.scatter(voltage,angle, c="r", marker='x')
plt.plot(voltage,slope*voltage + intercept)
plt.xlabel('voltage [volts]')
plt.ylabel('Angles [rad]')
plt.legend(['Lin. Reg.','Raw Data'])
plt.title('Regression of Sensor Data')
plt.grid()
plt.show()
and this is what I get
intercept = [-1.57 -1.26 -0.94 -0.63 -0.31  0.    0.31  0.65  0.96  1.23  1.52]
slope = [[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
Error:
ValueError: x and y must have same first dimension, but have shapes (1, 11) and (11, 11)
I did get a plot too but without any labels. Any idea?
Reply
#2
Remove .reshape everywhere. In variable definitions (angle and voltage) use [:, np.newaxis] instead (of reshape).

Inspect what shapes your variables angle and voltage have. LinearRegression expects that voltage is of shape (n_samples, n_features).
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Issue with plotting Dmorgan24 3 2,256 Jan-16-2019, 09:28 PM
Last Post: Dmorgan24

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020