Numpy in VS Code Ubuntu 20.04 - python-3.x

I am new to Ubuntu and is trying to get Numpy working on VS Code. Following is my code:
import matplotlib.pyplot as plt
import numpy as np
x = [1,2,3,4]
y = [3,5,7,9]
plt.grid(True)
plt.xlabel("My X values")
plt.ylabel("My Y values")
plt.plot(x,y, 'b-^', lineWidth = 3, markersize = 7, label = "Blue Line")
plt.legend(loc = "upper center")
plt.show()
But the debugger gives me the following error:
No module named 'numpy.core._multiarray_umath'
Does anyone knows how to install that module? Thank you so much in advance.

Related

Statsmodels.api.tsa.seasonal_decompose plot figsize

I am using statsmodels.api.tsa.seasonal_decompose to do some seasonal analysis of a time series.
I set it up using
decomp_viz = sm.tsa.seasonal_decompose(df_ts['NetConsumption'], period=48*180)
and then try and visualise it using
decomp_viz.plot()
The output was tiny so I tried to use the standard matplotlib command of
decomp_viz.plot(figsize=(20,20))
However, this got the warning:
TypeError: plot() got an unexpected keyword argument 'figsize'
The documentation says that a matplotlib.figure.Figure is returned from DecomposeResult.plot so I am unsure as to why this error is happening.
My version of statsmodels is 0.13.1 and I am aware that the documentation is for 0.14.0, but conda says that that version does not exist and that I cannot update to it.
Any thoughts would be appreciated.
DecomposeResult.plot doesn't pass keyword arguments. You can change the figure size after you create it:
import statsmodels.api as sm
import numpy as np
import matplotlib.pyplot as plt
PERIOD = 48*180
g = np.random.default_rng(20211225)
y = np.cos(2 * np.pi * np.linspace(0, 10.0, 10*PERIOD))
y += g.standard_normal(y.shape)
decomp_viz = sm.tsa.seasonal_decompose(y, period=PERIOD)
fig = decomp_viz.plot()
fig.set_size_inches((16, 9))
# Tight layout to realign things
fig.tight_layout()
plt.show()
Alternatively, you can do the same by altering the MPL rc.
import statsmodels.api as sm
import numpy as np
import matplotlib.pyplot as plt
# Change default figsize
plt.rc("figure",figsize=(20,20))
PERIOD = 48*180
g = np.random.default_rng(20211225)
y = np.cos(2 * np.pi * np.linspace(0, 10.0, 10*PERIOD))
y += g.standard_normal(y.shape)
decomp_viz = sm.tsa.seasonal_decompose(y, period=PERIOD)
decomp_viz.plot()
plt.show()
which produces (cropped as too big for my screen)

How to plot mode as a line using Python, Numpy, Matplotlib?

[Image here]
1I want to plot mode of as a line that comes from a bunch of lines. But I get value error as follows:
ValueError: x and y must have same first dimension, but have shapes (1, 159) and (2, 1, 159)
How to solve it?
My Code is as follows:
from glob import glob
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from scipy import stats
hvsra = []
for filename in glob('*.hv'):
with open(filename) as f:
hv = np.genfromtxt(f)
hv_m = np.ma.array(hv)
new_hv = hv_m[:,0:2]
freq = new_hv[:,0]
freq_new = np.reshape(freq_arr, (1, 159))
amp = new_hv[:,1]
hvsra.append(amp)
hvsr = np.array(hvsra)
hvsrm = stats.mode(hvsr)
plt.figure(figsize=(12, 8))
plt.loglog(freq_new,
hvsrm)
Thanks for your help.

Multiple plot single colorbar in python matplotlib basemap system crash problem

Why I am getting a runtime error while running this code?? I wanted to show two SST data in a single plot using for loop. while I am running the code it shows your system has crashed. I am sharing the screenshot of the system log.
Screenshot of the error
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from netCDF4 import Dataset
from mpl_toolkits.axes_grid1 import ImageGrid
def read_sst (x):
ncfile=x
fh=Dataset(ncfile,mode='r')
sst=fh.variables['sst'][:]
sst_anom=sst[0,:,:]
return sst_anom
sst_anom_drought=read_sst("Drought_SST_Mean_Anomaly_Composite_1901-2014.nc")
sst_anom_flood=read_sst("Flood_SST_Mean_Anomaly_Composite_1901-2014.nc")
SST_ncfile='Flood_SST_Mean_Anomaly_Composite_1901-2014.nc'
fh1=Dataset(SST_ncfile,mode='r')
lons = fh1.variables['longitude'][:]
lats = fh1.variables['latitude'][:]
sst_data=[sst_anom_drought,sst_anom_flood]
fig = plt.figure(1,(15.,5.))
grid_top = ImageGrid(fig, 111, nrows_ncols = (2, 1),axes_pad=0.5)
cbar_ax = fig.add_axes([0.25,0.15, 0.55, 0.015])
for g, s in zip(grid_top,sst_data):
plt.sca(g)
m = Basemap(resolution='l',projection='merc',llcrnrlon=30, llcrnrlat=-31,
urcrnrlon=360, urcrnrlat=65)
clevs = np.linspace(-0.8, 0.8, 15)
lons, lats = np.meshgrid(lons, lats)
xi, yi = m(lons, lats)
color_map = plt.cm.RdBu_r
#reversed_color_map = color_map.reversed()
cs = m.contourf(xi,yi,s,clevs,cmap=color_map,extend='both')
cb=fig.colorbar(cs,orientation="horizontal",cax=cbar_ax)
m.drawparallels(np.arange(-30., 65., 15.), labels=[1,0,0,0], fontsize=12,linewidth=0.1)
m.drawmeridians(np.arange(-180., 180., 40.), labels=[0,0,0,1], fontsize=12,linewidth=0.1)
m.fillcontinents(color='whitesmoke',lake_color='whitesmoke')
m.drawcoastlines()

when running gekko for 1st time, got this error "cannot import name 'dump_csp_header' from werkzeug.http'

I'm using Spyder to run Python 3.7 where I installed gekko. However, I tried running a simple gekko code from Wikipedia and it gives me the following error:
ImportError: cannot import name 'dump_csp_header' from 'werkzeug.http' (C:\Users\zulfan.adiputra\AppData\Local\Continuum\anaconda3\envs\PythonNew\lib\site-packages\werkzeug\http.py)
When I check in the Anaconda prompt, the werkzeug installed is 1.0.0. What to do in this regard?
Thanks
You can resolve the error with:
Set GUI=False in m.solve()
Run the Python program from the command line with python myProgram.py. There are sometimes problems with the Flask server if you try to use the GUI by running from an IDE like Spyder or IDLE.
Instead of using the GUI option, it is relatively easy to plot the results with matplotlib. Here is an example script:
from gekko import GEKKO
import numpy as np
import matplotlib.pyplot as plt
m = GEKKO() # initialize gekko
nt = 101
m.time = np.linspace(0, 2, nt)
# Variables
x1 = m.Var(value=1)
x2 = m.Var(value=0)
u = m.Var(value=0, lb=-1, ub=1)
p = np.zeros(nt) # mark final time point
p[-1] = 1.0
final = m.Param(value=p)
# Equations
m.Equation(x1.dt() == u)
m.Equation(x2.dt() == 0.5 * x1 ** 2)
m.Obj(x2 * final) # Objective function
m.options.IMODE = 6 # optimal control mode
m.solve() # solve
plt.figure(1) # plot results
plt.plot(m.time, x1.value, "k-", label=r"$x_1$")
plt.plot(m.time, x2.value, "b-", label=r"$x_2$")
plt.plot(m.time, u.value, "r--", label=r"$u$")
plt.legend(loc="best")
plt.xlabel("Time")
plt.ylabel("Value")
plt.show()

LaTeX was not able to process the following string: b'lp'

I just begin with Python, scypi and matplotlib, I had copy this code:
from scipy import stats
import numpy as np
import matplotlib.pyplot as plt
data = stats.exponweib.rvs(a=1, c=2.09, scale=10.895, loc=0, size=2500)
plt.plot(data, stats.exponweib.pdf(data, *stats.exponweib.fit(data, 1, 1, scale=02, loc=0))
_ = plt.hist(data, bins = np.linspace(0, 16, 33), normed=True, alpha=0.5)
plt.show()
But it show an error:
'LaTeX was not able to process the following string: b'lp''
The file ...Lib\site-packages\matplotlib\mpl-data\matplotlibrc show:
#text.usetex : False
os : windows 7
dis: winpython
What can I do?
Thanks.

Resources