I use pandas to read a csv file to do some analysis. But the returned type is pandas.core.series.Series, which can not be converted to num using the command matplotlib.dates.date2num. Below is my code:
import pandas as pd
import numpy as np
from bokeh.plotting import figure, output_file, show
import matplotlib.dates as mdates
import time
import matplotlib.pyplot as plt
AAPL = pd.read_csv(
"http://ichart.yahoo.com/table.csvs=AAPL&a=0&b=1&c=2009&d=0&e=1&f=2010",
parse_dates=['Date']
)
x = AAPL['Date']
y = AAPL['Close']
print type(x)
x = mdates.date2num(x)
z4 = np.polyfit(x, y, 6)
p4 = np.poly1d(z4)
xx = np.linspace(x.min(), x.max(), 100)
dd = mdates.num2date(xx)
plt.plot(dd,p4(xx))
The command print type(x) returns pandas.core.series.Series. This one x = mdates.date2num(x) returns the error as: AttributeError: 'numpy.datetime64' object has no attribute 'toordinal'.
Any one can shed a light on me for this issue?
Use x.astype(datetime) to convert to datetime.
from datetime import datetime
x = mdates.date2num(x.astype(datetime))
z4 = np.polyfit(x, y, 6)
p4 = np.poly1d(z4)
xx = np.linspace(x.min(), x.max(), 100)
dd = mdates.num2date(xx)
plt.plot(dd,p4(xx))
Related
I have successfully plotted an excel data to make a 3d plot. Now I want to plot it to make a contour map. But somehow it resulted an error. could someone help me?
This is my code:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df = pd.read_excel('book1.xlsx')
print(df.head())
fig, ax = plt.subplots(1,1)
x = df['Ex Wavelength(nm)']
y = df['Em Wavelength(nm)']
X, Y = np.meshgrid(x, y)
Z = df['Intensity(cnt)']
cp = ax.contourf(X, Y, Z)
fig.colorbar(cp)
plt.show()
Below is my code is written but I am getting the above-mentioned error. Can someone please help me in this regard? Thank you in advance.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
csv = pd.read_excel("Slider.xlsx",sheet_name="K",skiprows=2,usecols = "E");
data = pd.read_excel("Slider.xlsx",sheet_name="K",skiprows=2,usecols = "F");
x = csv
y = data
plt.scatter(x, y)
z = np.polyfit(x, y, 1)
p = np.poly1d(z)
plt.plot(x,p(x),"r--")
plt.show()
I am trying to graph this equation and am currently running into these errors. I am importing numpy and matplotlib with python. I am not sure how to fix these errors
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
def equation(delta=0.05):
#for K = 3
#from matplotlib.mlab import bivariate_normal
x = y = np.arange(0,1,delta)
#y = np.arange(0,1,delta)
#x = np.arange(0.4,1,delta)
X,Y = np.meshgrid(x,y)
Z = (3*y-y-9*x+2*3*x)**2 - 4(9*x-3*x)(y-3*y+3-3*x)
return X, Y, Z
#x = F
#y = P
fig = plt.figure()
#ax = fig.add_subplot(111, projection'3d')
ax = Axes3D(equation(0.05))
x,y,z = Axes3D.equation(0.05)
ax.plot_wireframe(x,y,z, rstride=5, cstride=5)
plt.show()
There is a Type Error when using x = y = np.arange(0,1,delta) which says that int is not callable. When using y = np.arange(0,1,delta) and x = np.arange(0.4,1,delta) instead, I am getting a Value Error
ValueError: operands could not be broadcast together with shapes (20,)
(12,).
welcome to StackOverflow!
There are several things that need fixing with your code-
As mentioned by Le Hoang Giang your multiplications are missing a couple of asterixes. When you write 4(9*x-3*x) python tries to use the "4" as a function, which is not callable, hence the error.
You need to calculate Z using X & Y (caps) not x,y, so you get a 2d surface.
Your usage of Axes3D is not according to the reference.
Please find below a working version of your code.
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
def equation(delta=0.05):
#for K = 3
#from matplotlib.mlab import bivariate_normal
x = y = np.arange(0,1,delta)
#y = np.arange(0,1,delta)
#x = np.arange(0.4,1,delta)
X,Y = np.meshgrid(x,y)
Z = (3*Y-Y-9*X+2*3*X)**2 - 4*(9*X-3*X)*(Y-3*Y+3-3*X)
return X, Y, Z
#x = F
#y = P
fig = plt.figure()
#ax = fig.add_subplot(111, projection'3d')
ax = Axes3D(fig)
x,y,z = equation(0.05)
ax.plot_wireframe(x,y,z, rstride=5, cstride=5)
plt.show()
You should write 4*(9*x-3*x)*(y-3*y+3-3*x), instead of 4(9*x-3*x)(y-3*y+3-3*x). Missing '*', your program can't understand it is multiple.
I'm trying to read a csv file that has a date that looks like this: 2018-02-20T22:41:33.793000Z and I can't figure out how to use that as the x axis in matplotlib. I obviously have no idea what I"m doing with datetime because I can't seem to get it to be usefull numbers for matplotlib.
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sys
import os
import matplotlib
import matplotlib.dates as mdates
import datetime
from datetime import datetime
data = pd.read_csv(os.path.join(os.path.dirname(__file__), 'new.csv'))
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
b = data.iloc[:, 8] #reading from column 8
a = pd.to_datetime(b, format='%Y-%m-%dT%H:%M:%S.%fZ', errors='ignore')
print(a)
x = a #date #.iloc[:, 0] grabs column without header
y = data.iloc[:, 2] #number #reading from column 2
z = data.iloc[:, 6] #quantity #reading from column 6
#c = data.bluered #blue or red
ax.scatter(x, y, z) #ax.scatter(x, y, z, c=c)
plt.xlim(-1, 35)
plt.ylim(0, 300)
ax.set_zlim(-1,150)
plt.show()
After much frustration I found the problem I was having was just simply to change plt.xlim(-1, 35) to plt.xlim('2018-02-20 22:41:26.419000','2018-02-20 22:48:55.768000')...which is the date/time range I was looking at.
I was wondering how could I reset the limit of my colorbar, such that it has axis from 0 to 16 instead of 0 to 14.
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from scipy.io import netcdf
import numpy as np
import os
fig = plt.figure(figsize=(16,6))
map=Basemap(projection='merc',llcrnrlat=-21.25,urcrnrlat=21.25,\
llcrnrlon=1.25,urcrnrlon=358.75,resolution='c')
map.drawcoastlines()
os.chdir( '/Users/wenyuz/Documents/')
f = netcdf.netcdf_file('precip.mon.mean.nc', 'r')
lon = f.variables['lon']
lat = f.variables['lat']
precip = f.variables['precip']
precip_tm=np.mean(precip[1:,27:45,:],0)
print np.shape(precip_tm)
delta = 2.5
long_west=1.25
long_east=358.75
lat_south=21.25
lat_north=-21.25
x = np.arange(long_west, long_east+delta, delta)
y = np.arange(lat_south, lat_north-delta, -delta)
X1, Y1=np.meshgrid(x,y)
X, Y = map(X1, Y1)
CS = map.contourf(X, Y, precip_tm,cmap=plt.cm.gist_ncar,vmin=0,vmax=16);
cbar = map.colorbar(CS,location="bottom")
cbar.set_clim(0, 16)
cbar.set_label('mm')
plt.title('GPCP: 1979-2008')
f.close()
somehow, if I replace map.contourf with map.pcolormesh it works to rest the colorbar limit.