I've been trying to draw a regression line for a multivariable regression, both ENGINESIZE and FUELCONSUMPTION_CITY are independent variables and CO2EMISSIONis the dependent variable.
I was trying to draw a regression line but no matter what, I'm not able to draw it as it keeps showing me the same error.
Below is my code:-
z_cord = regr.coef_[0][0]*train_engine[['ENGINESIZE']]
z_cod = regr.coef_[0][1]*train_engine[['FUELCONSUMPTION_CITY']]
s = y_cord.add(y_cod, fill_value=0)
l = []
for index, row in s.iterrows():
l.append(row['ENGINESIZE']+row['FUELCONSUMPTION_CITY'] + regr.intercept_)
z = pd.DataFrame(l,columns=['CO2EMISSION'])
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.scatter(data[['ENGINESIZE']],data[['FUELCONSUMPTION_CITY']],co2_data)
x = train_engine[['ENGINESIZE']]
y = train_engine[['FUELCONSUMPTION_CITY']]
ax.plot3D(x,y,z,color='red')
plt.show()
Every time i run it its giving me these errors
ValueError: input operand has more dimensions than allowed by the axis remapping
AttributeError: 'Line3D' object has no attribute '_verts3d'
the scatter plot is drawn when i comment ax.plot3D(x,y,z,color='red') line.
I don't know where I'm going wrong, some help would be appreciated.
In your code, x and y are two-dimensional. However, ax.plot3D requires x and y to be one-dimensional and you can make them one-dimensional by:
x = train_engine['ENGINESIZE']
y = train_engine['FUELCONSUMPTION_CITY']
Note that we can get number of dimensions of x and y by ndim:
x.ndim, y.ndim
Related
I'm pretty new on python. I have a piece of code that reads some data from a file, creates several arrays and plots them with plt.plot. The arrays are s for the x-axis, and P_abs_i and P_abs_e in the y-axis. The code was working fine until I tried to plot smooth lines instead of the dafault ones.
I tried to use the interpolate.interpid function to plot smooth lines. I used np.arrays to turn my arrays into numpy arrays, following the example in the interpid guide. I then used interpid to create a cubic interpolation curve and np.linspace to get evenly spaced samples. It worked for one of the lines (P_abs_e), so I then tried to copy the same process for the other line (P_abs_i) but I got the error message: "ValueError: x and y must have same first dimension, but have shapes (500,) and (1, 500)". Can somebody help? (The code is below, not sure if it's going to show properly since this is my first time posting):
x_e = np.array(s)
y_e = np.array(P_abs_e)
cubic_interpolation_model_e = interp1d(x_e, y_e, kind = "cubic")
X_e=np.linspace(x_e.min(), x_e.max(), 500)
Y_e=cubic_interpolation_model_e(X_e)
plt.plot(X_e, Y_e, 'b', label = 'e')
x_i = np.array(s)
y_i = np.array(P_abs_i)
cubic_interpolation_model_i = interp1d(x_i, y_i, kind = "cubic")
X_i=np.linspace(x_i.min(), x_i.max(), 500)
Y_i=cubic_interpolation_model_i(X_i)
plt.plot(X_i, Y_i, 'g', label = 'He3')
I am trying to plot (magnetic) field lines. I came to know stream function is the tool used to plot field lines. However, an error comes up telling ValueError: 'x' values must be equally spaced.
Please note that the code uses Fourier basis along x so it is equally spaced along x and uses Chebyshev basis along y and hence it is non-uniform grid along y. I do not understand why the code says "x must be uniformly spaced" when it's uniform along x.
The other thing I want to know is, how to plot field lines for a non-uniform grid?
Also is there any other method to plot field lines apart from streamplot?
Code that I am running is attached below for reference:
import numpy as np
import h5py
import matplotlib.pyplot as plt
f = h5py.File('./B_mm/Re_10k/Bx_v24/Bx_v24_s1.h5', 'r')
y = f['/scales/y/1.0'][:]
x = f['/scales/x/1.0'][:]
Bxtotal = f['/tasks/Bxtotal'][:]
Bytotal = f['/tasks/Bytotal'][:]
t = f['scales']['sim_time'][:]
print(np.shape(y))
print('y = ', y)
print(np.shape(x))
print('x= ', x)
X, Y = np.meshgrid(y,x)
print(np.shape(X))
print(np.shape(Y))
Bx = Bxtotal[len(Bxtotal)-1, :, :]
By = Bytotal[len(Bytotal)-1, :, :]
print(np.shape(Bx))
print(np.shape(By))
plt.figure(figsize=(4,4),facecolor="w")
plt.streamplot(X, Y, Bx, By, color='k', density=1.3, minlength=0.9, arrowstyle='-')
plt.show()
And this is my error message;
I'm trying to plot a line graph in Python using pyplot but I get an error, TypeError: 'float' object is not callable for this line of code:
ycoord = [math.pow(p(1-p),(i-1)) for i in range(1,51)]
I basically have a function p(1-p)^(i-1) that I need to plot a line graph with. I have an array of coordinates 1-51. And I need to get the corresponding y coordinates with that function.
I have also tried: p(1-p)**(i-1), but that has not worked either.
Here is my full code:
def test():
p = 0.2
plt.figure(1)
#create x coordinates [1-51]
xcoord = [i for i in range(1,51)]
#create y coordinates from formula
ycoord = [math.pow(p(1-p),(i-1)) for i in range(1,51)]
plt.plot(xcoord,ycoord)
plt.draw()
plt.show()
test()
The syntax for multiplication in Python is not the same as you may be used to when writing math equations, you can't omit the '*' symbol.
p (1-p)
should be:
p * (1-p)
The error is self explanatory,
ycoord = [math.pow(p(1-p),(i-1)) for i in range(1,51)]
In this block p is a floating point number, not a method name. If you have a function p that you want to call from here then rename this variable p to something else or vice versa.
Also if you meant (px(1-p))^(i-1) [p times (1-p) to the power i-1], you should do pow(p*(1-p), (i-1))
I had to create a contour graph (in python) based on a formula and several other parameters. My graph came out fine. However, my axis labels will not show. I have tried changing the code several times but I am actually a little lost as how to what my real problem is. I know it deals with the command to create the labels but understand the error message
Also, this is my first post and if you have recommendations for how I should ask questions, I would appreciate the help.
def contourf_plot():
T = np.linspace(0,30,50)
P = np.linspace(600,1000,50)
X, Y = np.meshgrid(T,P)
Z = (Y/100)*np.e**((12*X)/(X+243))
Z.shape
plt.figure()
CF = plt.contourf(T,P,Z,50)
plt.colorbar(CF)
plt.set_Tlabel("Temperature[$\degree$C]")
plt.set_Plabel("Pressure[Pa]")
plt.show()
return
if __name__ == "__main__":
contourf_plot()
Error message: 'module' object has no attribute 'set_Xlabel'
All you need to do is a slight change in your code. You are currently trying to add a label to the axes T and P, though they do not exist (it is still the x and y axes). T and P are just the data that you are trying to plot.
def contourf_plot():
T = np.linspace(0,30,50)
P = np.linspace(600,1000,50)
X, Y = np.meshgrid(T,P)
Z = (Y/100)*np.e**((12*X)/(X+243))
Z.shape
fig,ax = plt.subplots() #add this line
CF = plt.contourf(T,P,Z,50)
plt.colorbar(CF)
ax.set_xlabel("Temperature[$\degree$C]") #sets the x and y label
ax.set_ylabel("Pressure[Pa]")
plt.show()
return
if __name__ == "__main__":
contourf_plot()
This gives the image
I'm trying to show a contour plot using matplotlib from a complex array. The array is a 2x2 complex matrix, generated by the (C like) method:
for i in max_y:
for j in max_x:
pos_x = pos_x + step
z = complex(pos_x,pos_y)
c_arr[i][j] = complex_function(z)
pos_y = pos_y + step
I would like to plot this c_arr (real part) using contourplot, but so far the only thing that I can get from contour is
TypeError: Input z must be a 2D array.
The c_arr.real is a 2D array, and doesn't matter if I make a grid with x, y, or pos_x, or pos_y, the result is always the same. The docs from matplotlib tells me how to use it, but not the datatypes necessary to use it, so I feel left in the dark.
EDIT: Thanks for the answer. My problem now is that I have to get the complex values from a function in this form:
def f(z):
return np.sum(np.arange(n)*np.sqrt(z-1)**np.arange(n))
where the sum must be added up. How can this be accomplished using the meshgrid form that contour needs? Thanks again.
matplotlib.pyplot.contour() allows complex-valued input arrays. It extracts real values from the array implicitly:
#!/usr/bin/env python
import numpy as np
from matplotlib import pyplot as plt
# generate data
x = np.r_[0:100:30j]
y = np.r_[0:1:20j]
X, Y = np.meshgrid(x, y)
Z = X*np.exp(1j*Y) # some arbitrary complex data
# plot it
def plotit(z, title):
plt.figure()
cs = plt.contour(X,Y,z) # contour() accepts complex values
plt.clabel(cs, inline=1, fontsize=10) # add labels to contours
plt.title(title)
plt.savefig(title+'.png')
plotit(Z, 'real')
plotit(Z.real, 'explicit real')
plotit(Z.imag, 'imagenary')
plt.show()
real
explicit real
imagenary