Plot wind vectors with quiver() - python

I want to plot wind vectors. I use Basemap and this example http://basemaptutorial.readthedocs.org/en/latest/plotting_data.html#quiver.
In my file, the longitudes go from 0 to 360. I use latlon=True to shift it to -180:180. But, when I use "points" to define the point density, the vectors are plotted over half of my figure only.
Here is the code:
Of course, I use this code:
m=Basemap(projection='cyl',llcrnrlat=30,urcrnrlat=80, llcrnrlon=-40,urcrnrlon=40,resolution='c')
latvar=nc.variables['lat']
lat=latvar[:]
lon=nc.variables['lon'][:]
X,Y=m(lon,lat)
lons,lats=meshgrid(lon,lat)
X4,Y4=m(lons,lats)
varU=ncU.variables['var1'][0,0,:,:]
varV=ncV.variables['var2'][0,0,:,:]
speed=np.sqrt(varUvarU+varVvarV)
yy=np.arange(0,len(Y[:]),3)
xx=np.arange(0,len(X[:]),3)
points=np.meshgrid(yy,xx)
m.quiver(X4[points],Y4[points],varU[points],varV[points],speed[points],cmap=cmap‌​,latlon=True)
Can someone help me with this issue? Thanks.

You have a lot of things going on that I am not sure you need. I have tried your code with some minor modifications and it works:
import numpy
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
lon =NC.variables['lon'][:]
lat =NC.variables['lat'][:]
m=Basemap(projection='cyl',,llcrnrlat=30,urcrnrlat=80, llcrnrlon=-40,urcrnrlon=40,resolution='c')
lons,lats=numpy.meshgrid(lon,lat)
X4,Y4=m(lons,lats)
varU=NC.variables['var1'][0,0,:,:]
varV=NC.variables['var2'][0,0,:,:]
speed=numpy.sqrt(varU*varU+varV*varV)
yy=numpy.arange(0,len(lat),3)
xx=numpy.arange(0,len(lon),3)
points=numpy.meshgrid(yy,xx)
m.quiver(X4[points],Y4[points],varU[points],varV[points],speed[points],cmap=cmap,latlon=True)
plt.show()
# with all points for comparison
m.quiver(X4,Y4,varU,varV,speed,cmap=cmap,latlon=True)
plt.show()

Related

Plot scatter graphs with matplotlib subplot

I am trying to plot a scatter diagram. It will take multiple arrays as input but plot into a single graph.
Here is my code:
import numpy as np
import os
import matplotlib.pyplot as plt
ax = plt.gca()
n_p=np.array([17.2,25.7,6.1,0.9,0.5,0.2])
n_d=np.array([1,2,3])
a_p=np.array([4.3,1.4,8.1,1.8,7.9,7.0])
a_d=np.array([12,13,14])
ax.scatter = ([n_d[0]/n_d[1]],[n_p[0]/n_p[1]])
ax.scatter = ([a_d[0]/a_d[1]],[a_p[0]/a_p[1]])
I will read the arrays from csv file, here I just put a simple example (for that I imported os). I want to plot the ratio of array element 2/ element 1 of n_p (as x-axis) and same with n_d (as y-axis). This will give a point in the graph. Similar operation will be followed by a_p and a_d array, and the point will be appended to the graph. There will be more data to append, but to understand the process, two is enough.
I tried to follow example from here.
If I use the color, I get syntax error.
If I do not use color, I get a blank plot.
Sorry, my coding experience is beginner so code is rather nasty.
Thanks in advance.
remove the = from the function call!
import numpy as np
import os
import matplotlib.pyplot as plt
ax = plt.gca()
n_p=np.array([17.2,25.7,6.1,0.9,0.5,0.2])
n_d=np.array([1,2,3])
a_p=np.array([4.3,1.4,8.1,1.8,7.9,7.0])
a_d=np.array([12,13,14])
ax.scatter([n_d[0]/n_d[1]],[n_p[0]/n_p[1]])
ax.scatter([a_d[0]/a_d[1]],[a_p[0]/a_p[1]])

Struggling with piecewise polynomial interpolation in python

So I have this task, where im supposed to interpolate a function with polynomials. The entire interval is divided into N subintervals, and the polynomial interpolating in each subinterval is of order k. I generet all my interpolating points, but I am running into two problems.
I) For k=1, i.e first order polynomials, I've tried solving the task by having a loop generate a first order polynomial in each subinterval using the scipy interp1d, but I'd like to get all the different polynomials in a single plot.
This is my code, tried only including the nessescary bits, sorry if something is missing. intpoint here are the interpolation points, and funky(x) is just the arbitrary function im approximating.
import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate as sc
intpoint=np.array([-3,-2,-1,0,1,2,3])
for i in range(len(intpoint)):
intleng=[intpoint[i],intpoint[i+1]]
myinterval=np.linspace(intpoint[i],intpoint[i+1],1000)
mypol=sc.interp1d(intleng,np.sin(intleng),1)
plt.plot(intleng, mypol(intleng))
plt.plot(myinterval,np.sin(myinterval))
plt.show()
Apologies in advance if anything is unclear, or my code is hard to follow/untidy.
import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate as sc
intpoint=np.array([-3,-2,-1,0,1,2,3])
for i in range(len(intpoint)-1):
intleng=[intpoint[i],intpoint[i+1]]
myinterval=np.linspace(intpoint[i],intpoint[i+1],1000)
mypol=sc.interp1d(intleng,np.sin(intleng),1)
plt.plot(myinterval,mypol(myinterval))
plt.plot(myinterval,np.sin(myinterval))
plt.show()
I think this is what you want. There was a mistake in the plotting and you should do plt.show() only once to get one plot.

Python : Basemap barbs , wind vector plotting on map

I'm trying to plotting wind vector on map using basemap.barbs.
I try to draw it as a test with simple code.
No error message is shown with this code, Even if I wait, the picture does not come out..
If a picture is being drawn, the picture does not come out even after waiting a long time.
I think there seems to be something else wrong.
It is the first time to draw a wind field with Python, so I'm immature.
Is it because of the high data resolution? (Its len(lon) is 360, len(lat) is 200)
Or is it another matter?
import netCDF4 as nc
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap,addcyclic,shiftgrid
data=nc.Dataset('wind.nc','r')
lon=data.variables['XU_OCEAN'][:]
lat=data.variables['YU_OCEAN'][:]
time=data.variables['TIME1'][:]
uwind=data.variables['WIND_POWER_U'][:]
vwind=data.variables['WIND_POWER_V'][:]
uwind_DJF=[]
vwind_DJF=[]
for i in range(11,20*12+1,12):
uwind_DJF.append((uwind[i]+uwind[i+1]+uwind[i+2])/3)
vwind_DJF.append((vwind[i]+vwind[i+1]+vwind[i+2])/3)
uwind_DJF=np.mean(uwind_DJF,axis=0) ##shape is (200,360)
vwind_DJF=np.mean(vwind_DJF,axis=0) ##shape is (200,360)
fig=plt.figure(figsize=(12,9))
m=Basemap(resolution='l',projection='cyl',llcrnrlon=-90,llcrnrlat=30,urcrnrlon=80,urcrnrlat=70)
m.drawparallels(np.arange(-90,90,30),labels=[1,0,1,0],fontsize=10)
m.drawmeridians(np.arange(-180,180,45),labels=[0,0,0,1],fontsize=10)
m.drawcoastlines()
m.drawstates()
m.drawcountries()
lon2d,lat2d=np.meshgrid(lon,lat)
x,y=m(lon2d,lat2d)
m.barbs(x,y,uwind_DJF,vwind_DJF)
plt.show()

pcolormesh draws not points but lines between data points

I need to plot data of rain summas (from satellite observations) onto a map from grib2 files. Finally I managed to load the data via text files into numpy arrays and tie it with picture coordinates using Basemap. But problem is that Python do not put the coloured points from the data, but tends to draw lines between neighbouring points in data field, so the plot looks ugly.
I do not see the source of the problem.
Fragments of my code are:
import numpy as np
import matplotlib
matplotlib.use('Agg')
from scipy import *
from pylab import *
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import cm
After that I read the data needed and produce 3 numpy arrays with shapes approximately (100000, 2), which contain respectively latitude, longitude, in degrees and the value of each data point. I visualize it using these commands:
def joonista(lats,lons,value,nimi,clevs,koloriit):
---------fragment of described reshaping (not shown), produces arrays "lats", "lons", "value"------------
map=Basemap(projection='aea',lat_1=30,lat_2=50,lat_0=45,lon_0=0,llcrnrlon=-30,llcrnrlat=20,urcrnrlon=80,urcrnrlat=53,resolution='l',)
x, y = map(lons, lats)
map.drawcoastlines(linewidth=0.17,color='0.7')
map.drawcountries(linewidth=0.17,color='0.7')
map.drawmeridians(np.arange(-50,60,5),linewidth=0.17,color='0.7',labels=[False,False,False,True])
map.drawparallels(np.arange(-25, 70, 5),linewidth=0.17,color='0.7',labels=[True,False,False,False])
varvid=mpl.colors.ListedColormap(koloriit)
norm = mpl.colors.BoundaryNorm(clevs,varvid.N)
cs = map.pcolormesh(x,y,value,cmap=varvid,norm=norm)
savefig(nimi,dpi=300)
plt.clf()
joonista(latA,lonA,valueA,'h05',[-1,0.00001,0.001,0.01,0.1,0.3,0.5,1,2,3,4,5,6,7,8,9,10,11,12,13],['k','c','#a0fff9','#00b354','#69b300','#97ff03','#C2524D','#FF7500','#b3a900','#fff551','#515bff','#45adff','#da000d','#ff2a36','#ffa0a5','#f003ff','#f778ff','0.5','0.75'])
joonista(latB,lonB,valueB,'h04',[-1,0.0000000000001,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18],['k','c','#a0fff9','#00b354','#69b300','#97ff03','#C2524D','#FF7500','#b3a900','#fff551','#515bff','#45adff','#da000d','#ff2a36','#ffa0a5','#f003ff','#f778ff','0.5','0.75'])
Here is an example picture:
I would be grateful, if I am told how to solve this problem.
Aleksei
Using Joe Kington recommendation, I replaced command
cs=map.pcolormesh(x,y,value,cmap=varvid,norm=norm)
by command
cs=plt.scatter(x,y,c=value,s=0.6, edgecolors='none',marker=',',cmap=varvid,norm=norm)
which well visualises precipitation distribution.
Thanks for assistance!

Scatter plot with a huge amount of data

I would like to use Matplotlib to generate a scatter plot with a huge amount of data (about 3 million points). Actually I've 3 vectors with the same dimension and I use to plot in the following way.
import matplotlib.pyplot as plt
import numpy as np
from numpy import *
from matplotlib import rc
import pylab
from pylab import *
fig = plt.figure()
fig.subplots_adjust(bottom=0.2)
ax = fig.add_subplot(111)
plt.scatter(delta,vf,c=dS,alpha=0.7,cmap=cm.Paired)
Nothing special actually. But it takes too long to generate it actually (I'm working on my MacBook Pro 4 GB RAM with Python 2.7 and Matplotlib 1.0). Is there any way to improve the speed?
Unless your graphic is huge, many of those 3 million points are going to overlap.
(A 400x600 image only has 240K dots...)
So the easiest thing to do would be to take a sample of say, 1000 points, from your data:
import random
delta_sample=random.sample(delta,1000)
and just plot that.
For example:
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
import random
fig = plt.figure()
fig.subplots_adjust(bottom=0.2)
ax = fig.add_subplot(111)
N=3*10**6
delta=np.random.normal(size=N)
vf=np.random.normal(size=N)
dS=np.random.normal(size=N)
idx=random.sample(range(N),1000)
plt.scatter(delta[idx],vf[idx],c=dS[idx],alpha=0.7,cmap=cm.Paired)
plt.show()
Or, if you need to pay more attention to outliers, then perhaps you could bin your data using np.histogram, and then compose a delta_sample which has representatives from each bin.
Unfortunately, when using np.histogram I don't think there is any easy way to associate bins with individual data points. A simple, but approximate solution is to use the location of a point in or on the bin edge itself as a proxy for the points in it:
xedges=np.linspace(-10,10,100)
yedges=np.linspace(-10,10,100)
zedges=np.linspace(-10,10,10)
hist,edges=np.histogramdd((delta,vf,dS), (xedges,yedges,zedges))
xidx,yidx,zidx=np.where(hist>0)
plt.scatter(xedges[xidx],yedges[yidx],c=zedges[zidx],alpha=0.7,cmap=cm.Paired)
plt.show()
What about trying pyplot.hexbin? It generates a sort of heatmap based on point density in a set number of bins.
You could take the heatmap approach shown here. In this example the color represents the quantity of data in the bin, not the median value of the dS array, but that should be easy to change. More later if you are interested.

Categories

Resources