I'm having a bit of trouble plotting polygon/multipolygon data with Geoviews. I have made a geodataframe that combines my two datasets together nicely. I am able to plot the data easily using the plot function:
See below:
import geopandas as gpd
import numpy as np
import pandas as pd
import holoviews as hv
import geoviews as gv
import geoviews.feature as gf
import cartopy
import cartopy.feature as cf
from geoviews import opts
from cartopy import crs as ccrs
gv.extension('bokeh')
Drop_na.plot(column = 'Registrations',figsize=(10,10), legend=True)
This gives me the below chart:
However, when I try to plot the same using GeoViews with the code below:
gv.Polygons(Drop_na, vdims=['Registrations']).opts(
tools=['hover'], width=550, height=700, color_index='Registrations',
colorbar=True, toolbar='above', xaxis=None, yaxis=None, padding=0.1)
I get the following error: "While projecting a Polygons element from a PlateCarree coordinate reference system (crs) to a PlateCarree projection none of the projected paths were contained within the bounds specified by the projection. Ensure you have specified the correct coordinate system for your data."
I've read around the documentation and have tried different ways of messing around with the projection method but i just can't get it generate the same chart or any chart for that matter.
Does anyone know what i'm doing wrong?
Kind regards,
Amen
Related
I have exported a large Matrix from Matlab to a data.dat file, which is tab delimited. I am importing this data into a iPython script to use seaborn to create a heatmap of the matrix using the following script:
import numpy as np
import seaborn as sns
import matplotlib.pylab as plt
uniform_data = np.loadtxt("data.dat", delimiter="\t")
ax = sns.heatmap(uniform_data, linewidth=0.0)
plt.show()
This code runs fine and outputs a correct heatmap. For small matrices, the output has a nice variation indicating the matrix elements:
However, if the size of the matrix increases in size, the result seems to have a uniform colour, which indicates that the result needs to be normalised:
which does not seem to contain any extractable information. How can I address this?
Sample result I want to color code the circle plots in my scatter and associate them with a legend.
I have made various attempts at a solution referencing matplotlib.org and this website. All to no avail.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
hysector = pd.read_csv('LF98TRUU_Lvl3_sector.csv',index_col=0)
hysector.plot.scatter(x='OAD',y='OAS',s=hysector['Wgt']*35,label='Sector');
This seems like it's going to be something simple that will fix my code but I think I've just looked at the code too much at the moment and need to get some fresh eyes on it. I'm simply trying to bring in a Grib2 file that I've downloaded from NCEP for the HRRR model. According to their information the grid type is Lambert Conformal with the extents of (21.13812, 21.14055, 47.84219, 47.83862) for the latitudes of the corners and (-122.7195, -72.28972, -60.91719, -134.0955) for the longitudes of the corners for the models domain.
Before even trying to zoom into my area of interest I just wanted to simply display an image in the appropriate CRS however when I try to do this for the domain of the model I get the borders and coastlines to fall within that extent but the actual image produced from the Grib2 file is just zoomed into. I've tried to use extent=[my domain extent] but it always seems to crash the notebook I'm testing it in. Here is my code and the associated image that I get from it.
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy
from mpl_toolkits.basemap import Basemap
from osgeo import gdal
gdal.SetConfigOption('GRIB_NORMALIZE_UNITS', 'NO')
plt.figure()
filename='C:\\Users\\Public\\Documents\\GRIB\\hrrr.t18z.wrfsfcf00.grib2'
grib = gdal.Open(filename, gdal.GA_ReadOnly)
z00 = grib.GetRasterBand(47)
meta00 = z00.GetMetadata()
band_description = z00.GetDescription()
bz00 = z00.ReadAsArray()
latitude_south = 21.13812 #38.5
latitude_north = 47.84219 #50
longitude_west = -134.0955 #-91
longitude_east = -60.91719 #-69
fig = plt.figure(figsize=(20, 20))
title= meta00['GRIB_COMMENT']+' at '+meta00['GRIB_SHORT_NAME']
fig.set_facecolor('white')
ax = plt.axes(projection=ccrs.LambertConformal())
ax.add_feature(cartopy.feature.BORDERS, linestyle=':')
ax.coastlines(resolution='110m')
ax.imshow(bz00,origin='upper',transform=ccrs.LambertConformal())
plt.title(title)
plt.show()
Returns Just Grib File
If I change:
ax = plt.axes(projection=ccrs.LambertConformal()
to
ax = plt.axes(projection=ccrs.LambertConformal(central_longitude=-95.5,
central_latitude=38.5,cutoff=21.13)
I get my borders but my actual data is not aligned and it creates what I'm dubbing a Batman plot.
Batman Plot
A similar issue occurs even when I do zoom into the domain and still have my borders present. The underlying data from the Grib file doesn't change to correspond to what I'm trying to get.
So as I've already said this is probably something that is an easy fix that I'm just missing but if not, it would be nice to know what step or what process I'm screwing up that I can learn from so that I don't do it in the future!
Updated 1:
I've added and changed some code and am back to getting only the image to show without the borders and coastlines showing up.
test_extent = [longitude_west,longitude_east,latitude_south,latitude_north]
ax.imshow(bz00,origin='upper',extent=test_extent)
This gives me the following image.
Looks exactly like image 1.
The other thing that I'm noticing which maybe the root cause of all of this is that when I'm printing out the value for plt.gca().get_ylim() and plt.gca().get_xlim() I'm getting hugely different values depending on what is being displayed.
It seems that my problem arises from the fact that the Grib file regardless of whether or not it can be displayed properly in other programs just doesn't play nicely with Matplotlib and Cartopy out of the box. Or at the very least does not with the Grib files that I was using. Which for sake of this perhaps helping others in the future are from the NCEP HRRR model that you can get here or here.
Everything seems to work nicely if you convert the file from Grib2 format to NetCDF format and I was able to get what I wanted with the borders, coastlines, etc. on the map. I've attached the code and the output below to show how it worked. Also I hand picked a single dataset that I wanted to display to test versus my previous code so incase you want to look at the rest of datasets available in the file you'll need to utilize ncdump or something similar to view the information on the datasets.
import numpy as np
from netCDF4 import Dataset
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy
import cartopy.feature as cfeature
from osgeo import gdal
gdal.SetConfigOption('GRIB_NORMALIZE_UNITS', 'NO')
nc_f = 'C:\\Users\\Public\\Documents\\GRIB\\test.nc' # Your filename
nc_fid = Dataset(nc_f, 'r') # Dataset is the class behavior to open the
# file and create an instance of the ncCDF4
# class
# Extract data from NetCDF file
lats = nc_fid.variables['gridlat_0'][:]
lons = nc_fid.variables['gridlon_0'][:]
temp = nc_fid.variables['TMP_P0_L1_GLC0'][:]
fig = plt.figure(figsize=(20, 20))
states_provinces = cfeature.NaturalEarthFeature(category='cultural', \
name='admin_1_states_provinces_lines',scale='50m', facecolor='none')
proj = ccrs.LambertConformal()
ax = plt.axes(projection=proj)
plt.pcolormesh(lons, lats, temp, transform=ccrs.PlateCarree(),
cmap='RdYlBu_r', zorder=1)
ax.add_feature(cartopy.feature.BORDERS, linestyle=':', zorder=2)
ax.add_feature(states_provinces, edgecolor='black')
ax.coastlines()
plt.show()
Final Preview of Map
I'm trying to animate a heat map of some information regarding geographic locations in Pittsburgh using matplotlib and basemap in Python 3. Right now I'm having issues getting basemap to use ARCGis imagery as the background. The following code only produces a blue square
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
m =Basemap(llcrnrlon=40.361369,llcrnrlat=-80.0955278,
urcrnrlon=40.501368,urcrnrlat=-79.865723,epsg=2272)
m.arcgisimage(service='ESRI_StreetMap_World_2D', xpixels=7000,dpi=96,verbose=True)
I've pulled down and run several examples from the internet about how to use arcgis images with basemap and they have run so I'm pretty sure its not a connection issue. I've tried several different projections and EPSG's including the world and US EPSGs, but no luck. Any help would be appreciated.
You have the longitudes and latitudes mixed up (see here):
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
m = Basemap(
llcrnrlat=40.361369, llcrnrlon=-80.0955278,
urcrnrlat=40.501368, urcrnrlon=-79.865723,
epsg = 2272
)
m.arcgisimage(service='ESRI_StreetMap_World_2D', xpixels=7000, verbose=True)
plt.show()
produces this image:
Plotting a very, very simple map of only europe in matplotlib / basemap takes so much time (around 10 seconds!). This is just unreal!?
Setting of resolution is only "l" (low).
Here is the very simple code:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
m = Basemap(projection='stere',lon_0=5,lat_0=90.0,rsphere=6371200.,\
llcrnrlon=-25.0,urcrnrlon=72.0,llcrnrlat=26.0,urcrnrlat=65.0,resolution='l')
m.drawcoastlines(linewidth=0.2)
m.drawcountries(linewidth=0.2)
plt.savefig('/var/www/map.png')
I need to plot hundreds of these maps every 2 hours. This would be impossible? :( Only idea is: Create an empty Basemap and try to draw boundaries with a shapefile.
Regards,
John