I've drawn a contour plot using matplolib and i want to overly this plot over folium map or is there any way to draw contour plot on map using folium
This is my code
import json
import numpy as np
from scipy.interpolate import griddata
from matplotlib import pyplot as plt
f = open('data.json', 'r')
data = json.load(f)
temp = data['temp']
lon = data['lon']
lat = data['lat']
x = np.linspace(min(lon), max(lon), 100)
y = np.linspace(min(lat), max(lat), 100)
X,Y = np.meshgrid(x, y)
Z = griddata((lon, lat), temp, (X, Y), method='cubic')
plt.contour(X,Y, Z)
plt.show()
My data file data.json, below is how my plot looks now i want to plot this over map
it's not clear your geometry is correct, have reversed lat & lon
straight forward with https://pypi.org/project/geojsoncontour/
import json
import numpy as np
from scipy.interpolate import griddata
from matplotlib import pyplot as plt
import geojsoncontour
import geopandas as gpd
f = open('data.json', 'r')
data = json.load(f)
temp = data['temp']
lon = data['lon']
lat = data['lat']
y = np.linspace(min(lon), max(lon), 100)
x = np.linspace(min(lat), max(lat), 100)
X,Y = np.meshgrid(x, y)
Z = griddata((lat, lon), temp, (X, Y), method='cubic')
contour = plt.contour(X,Y, Z)
gdf = gpd.GeoDataFrame.from_features(json.loads(geojsoncontour.contour_to_geojson(
contour=contour,
min_angle_deg=3.0,
ndigits=5,
stroke_width=1))).set_crs("EPSG:4326")
m = gdf.explore(color=gdf["stroke"])
plt.show()
m
Related
I am trying to regrid my .nc data with irregular grid with the following code:
from mpl_toolkits.basemap import Basemap
from netCDF4 import Dataset as NetCDFFile
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import griddata
nc = NetCDFFile('test.nc')
lat = nc.variables['latitude'][:]
lon = nc.variables['longitude'][:]
time = nc.variables['time'][:]
ssi = nc.variables['solar_irradiation'][:]
XI = np.arange(46.025, 56.525, 0.05)
YI = np.arange(5.025, 15.525, 0.05)
lat_new, lon_new = np.meshgrid(XI, YI)
new_grid = griddata((lat, lon), ssi, (lat_new, lon_new), method='linear')
It works fine, there are NaN values at lat/lon boxes which are not in the original file.
Then I want to plot it using Basemap:
map = Basemap(projection='merc', llcrnrlon=-5., llcrnrlat=35., urcrnrlon=30., urcrnrlat=60.,
resolution='i')
map.drawcountries()
map.drawcoastlines()
x, y = map(XI, YI)
rad = map.contourf(x, y, new_grid)
cb = map.colorbar(rad, "bottom", size="10%", pad="10%")
I am receiving following error: IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed. I know that this means, but I have no clue how to change to code so that it worked the same way. Thank you for every help!
I'm working with netCDF file for plotting the map. However, I'm new to it and there is very little progress and all I did is learning some tutorials. I have some difficulties when overlaying color onto the map. Here is my code (with the downloaded file):
from mpl_toolkits.basemap import Basemap, cm
from netCDF4 import Dataset
import numpy as np
import matplotlib.pyplot as plt
data = Dataset('filename','r')
lat = data.variables['lat'][:]
lon = data.variables['lon'][:]
time = data.variables['time'][:]
lwe_thickness = data.variables['lwe_thickness'][:]
data.close()
mp = Basemap(projection = 'mill',
llcrnrlon=lon.min(),
urcrnrlon=lon.max(),
llcrnrlat=lat.min(),
urcrnrlat=lat.max(),
resolution = 'c')
x, y = np.meshgrid(lon, lat)
x, y = mp(lon, lat)
mp.drawcoastlines()
mp.drawstates()
mp.drawcountries()
mp.drawmapboundary()
parallels = np.arange(0.,90,30.)
mp.drawparallels(parallels,labels=[1,0,0,0])
meridians = np.arange(-180.,180.,30.)
mp.drawmeridians(meridians,labels=[0,0,0,1])
cmesh = mp.pcolormesh(x,y,lwe_thickness,shading='flat',cmap=plt.cm.jet,latlon=True)
cbar = mp.colorbar(cmesh, location='right')
plt.show()
I am reading data from a csv file and plotting contours using python. The code works but when I check shapefile created, I can see only few contour lines are getting plotted whereas when I check image plot there are many more lines. What is going wrong in this code? I think the cs.collections is creating some problem but I am not able to figure it out.
import os
import numpy as np
import pandas as pd
from matplotlib.mlab import griddata
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
from shapely.geometry import mapping, Polygon, LineString,MultiLineString
import fiona
# set up plot
plt.clf()
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, axisbg='w', frame_on=False)
# grab data
data = pd.read_csv('Filename.csv', sep=',')
norm = Normalize()
# define map extent
lllon = -180
lllat = -90
urlon = 180
urlat = 90
# Set up Basemap instance
m = Basemap(#projection = 'merc',llcrnrlon = lllon, llcrnrlat = lllat, urcrnrlon = urlon, urcrnrlat = urlat,resolution='h', epsg=4326)
# transform lon / lat coordinates to map projection
data['projected_lon'], data['projected_lat'] = m(*(data.CLON.values, data.CLAT.values))
# grid data
numcols, numrows = 100, 100
xi = np.linspace(data['projected_lon'].min(), data['projected_lon'].max(), numcols)
yi = np.linspace(data['projected_lat'].min(), data['projected_lat'].max(), numrows)
xi, yi = np.meshgrid(xi, yi)
# interpolate
x, y, z = data['projected_lon'].values, data['projected_lat'].values, data.PRES.values
zi = griddata(x, y, z, xi, yi)
# contour plot
cs = plt.contour(xi, yi, zi,zorder=4)
plt.show()
lenvar = (len(cs.collections)) #number of contours
print(lenvar)
#print(cs.collections)
lines = [] # Empty list for contour sections
for i in range(lenvar):
n = i
p = cs.collections[i].get_paths()[0]
v = p.vertices # getting the individual verticies as a numpy.ndarray
x = v[:,0] #takes first column
y = v[:,1] #takes second column
line = LineString([(i[0], i[1]) for i in zip(x,y)]) #Defines Linestring
lines.append(line) #appends to list
schema = {'geometry': 'LineString','properties': {'id': 'int'}} # sets up parameter for shapefile
with fiona.open('ConShp.shp', 'w', 'ESRI Shapefile', schema) as c: # creates new file to be written to
for j in range(len(lines)):
l = (lines[j]) # creates variable
print(l)
print(type(l))
c.write({'geometry': mapping(l),'properties': {'id': j},})
data Sample is like:
Lat, Lon, Value
18.73, 26.34, 5000
20.00, 60.00, 7000
Shapefile_plot_in_GIS
Image of Plot in python
I am trying to plot a contour and quiver plot over a basemap. When I plot, I get no errors, but only the basemap will show. The netcdf file only has one point in it for lat and long, so I had to create a range of coordinates. Any ideas why this is happening?
import netCDF4
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import pylab
from mpl_toolkits.basemap import Basemap
from matplotlib.patches import Polygon
ncfile = netCDF4.Dataset('30JUNE2012_0400UTC.cdf', 'r')
dbZ = ncfile.variables['MAXDBZF']
u = ncfile.variables['UNEW']
v = ncfile.variables['VNEW']
#print u
#print v
#print dbZ
data = dbZ[0,0]
data.shape
#print data.shape
z_index = 0 # z-level you want to plot (0-19)
U = u[0,z_index, :,:] #[time,z,x,y]
V = v[0,z_index, :,:]
lats = np.linspace(35.0, 41.0, data.shape[0])
lons = np.linspace(-81.0,-73.0, data.shape[1])
# create the map
map = Basemap(llcrnrlat=36,urcrnrlat=40,\
llcrnrlon=-80,urcrnrlon=-74,lat_ts=20,resolution='c')
# load the shapefile, use the name 'states'
map.readshapefile('st99_d00', name='states', drawbounds=True)
# collect the state names from the shapefile attributes so we can
# look up the shape obect for a state by it's name
state_names = []
for shape_dict in map.states_info:
state_names.append(shape_dict['NAME'])
ax = plt.gca() # get current axes instance
x,y = map(*np.meshgrid(lats,lons))
levels = np.arange(5,60,3)
c = map.contourf(x,y,data, levels, cmap='jet')
plt.colorbar()
q=plt.quiver(U,V,width=0.002, scale_units='xy',scale=10)
qk= plt.quiverkey (q,0.95, 1.02, 20, '20m/s', labelpos='N')
plt.show()
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.