I have created a map like this:
The problem with it is that on the right side of the map is always a little bit offsite. I have set the bounds to:
ax.set_xlim(-215800,
1000000)
ax.set_ylim(3402659,
4879248)
No matter how I increase the xlim, or set margin the right side is still outside the bounds of the canvas. Can somebody help?
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from osgeo import ogr
import matplotlib.pyplot as plt
import matplotlib as mpl
import rasterio
import cartopy.crs as ccrs
import geopandas
from geopandas import *
from matplotlib import colors
MediumApple='#55FF00'
Cantaloupe='#FFA77F'
Marsred='#FF0000'
crs = ccrs.UTM(zone=10)
ax = plt.axes(projection=crs)
import matplotlib.patches as mpatches
for county in CAcountylist:
with rasterio.drivers():
with rasterio.open(r"CA\%s \%s.tif"%(county,county),"r") as src:
meta = src.meta
im=src.read().astype('f')
im=np.transpose(im,[1,2,0])
print im.shape
print im.min(),im.max()
im[im==0]=np.nan
im=im.squeeze()
xmin = src.transform[0]
xmax = src.transform[0] + src.transform[1]*src.width
print src.width,src.height
ymin = src.transform[3] + src.transform[5]*src.height
ymax = src.transform[3]
colors=[MediumApple,Cantaloupe,Marsred]
cmap=mpl.colors.ListedColormap([MediumApple,Cantaloupe,Marsred])
bounds_color=[1,1,2,2,3,3]
norm=mpl.colors.BoundaryNorm(bounds_color,cmap.N)
print xmin,xmax,ymin,ymax
ax.imshow(im, origin='upper', extent=[xmin,xmax,ymin,ymax], transform=crs, interpolation='nearest',cmap=cmap,norm=norm)
df=GeoDataFrame.from_file(r"\CACounty.shp")
df=df.to_crs(epsg=26910)
df.plot(axes=ax,alpha=0)
bounds = df.geometry.bounds
ax.set_xlim(-215800,
1000000)
ax.set_ylim(3402659,
4879248)
low_patch = mpatches.Patch(color='#55FF00', label='Low')
Moderate_patch = mpatches.Patch(color='#FFA77F', label='Moderate')
High_patch = mpatches.Patch(color='#FF0000', label='High')
plt.legend(handles=[low_patch,Moderate_patch,High_patch],loc=3)
plt.show()
Related
I'm trying to plot netcdf raster values of snowfall data in a text format overlaying what I currently have (mentioned further below). Example, something like this below:
Example
This is all the relevant code I have so far. I excluded the non relevant code. I tried plt.text and it gave me "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"
What I have plotted so far
import numpy
from datetime import datetime
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import cartopy.mpl.ticker as cticker
import matplotlib.pyplot as plt
from matplotlib import ticker, patheffects
from metpy.units import units
import numpy as np
import numpy.ma as ma
from scipy.ndimage import gaussian_filter, maximum_filter, minimum_filter
import xarray as xr
from metpy.plots import USCOUNTIES
from gradient import Gradient
import pandas as pd
import matplotlib.colors as col
#Open NOAA Snowfall dataset
ds = xr.open_dataset('sfav2_CONUS_2021093012_to_2022042512.nc')
ds
lat = ds.lat
lon = ds.lon
#converts snowfall data to inches
snowdata = ds['Data'] * 39
plt.text(lon, lat, snowdata, transform=datacrs)
As far as I know there isn't a vectorized way of plotting text (plt.text or plt.annotated). So you'll have to loop over the arrays and plot each point.
import matplotlib.pyplot as plt
import matplotlib.patheffects as PathEffects
import cartopy.crs as ccrs
import numpy as np
data = np.random.rand(18, 9)
lons, lats = np.mgrid[-17:18:2, 8:-9:-2]
lons = lons * 10
lats = lats * 10
fig, ax = plt.subplots(figsize=(10, 5), dpi=86, facecolor="w", subplot_kw=dict(projection=ccrs.EqualEarth()))
ax.pcolormesh(lons, lats, data, cmap="coolwarm", alpha=.2, transform=ccrs.PlateCarree())
ax.coastlines()
for val, lat, lon in zip(data.flat, lats.flat, lons.flat):
ax.text(
lon, lat, f"{val:1.1f}", ha="center", va="center", transform=ccrs.PlateCarree(),
path_effects=[PathEffects.withStroke(linewidth=3, foreground="w", alpha=.5)],
)
I'm using inset_axes() to control the placement of my colorbar legend. The label hangs off the plot just a little bit. Is there a way to just nudge it over without having to do bbox_to_anchor()? Some way to do an offset from the loc parameter? I do want to keep it in the lower left.
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
set1 = ax2.scatter(df.x, df.y,
edgecolors = 'none',
c = df.recommended_net_preferred_for_analysis_meters,
norm = mcolors.LogNorm(), cmap='jet')
cbaxes = inset_axes(ax2, width="30%", height="3%", loc=3)
plt.colorbar(set1, cax=cbaxes, format = '%1.2f', orientation='horizontal')
cbaxes.xaxis.set_ticks_position("top")
this is the code(I want to know the peak of the picture but I don't know how to add this kind of code)
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from scipy import stats
n=25
p=0.6
k=np.arange(0,50)
#the pmf forming
picture=stats.binom.pmf(k,n,p)
print(picture)
mpl.rcParams['font.sans-serif'] = [u'SimHei']
mpl.rcParams['axes.unicode_minus'] = False
mean,var,skew,kurt=stats.binom.stats(n,p,moments='mvsk')
print(mean,var,skew,kurt)
#the picture forming
plt.plot(k,picture,'o-')
plt.grid(True)
plt.show()
You can use scatter
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from scipy import stats
n=25
p=0.6
k=np.arange(0,50)
#the pmf forming
picture=stats.binom.pmf(k,n,p)
mpl.rcParams['font.sans-serif'] = [u'SimHei']
mpl.rcParams['axes.unicode_minus'] = False
mean,var,skew,kurt=stats.binom.stats(n,p,moments='mvsk')
print(mean,var,skew,kurt)
#the picture forming
plt.plot(k,picture,'o-')
plt.grid(True)
# the two new lines
max_ind = np.argmax(picture)
plt.scatter(x=k[max_ind],y=picture[max_ind],c='r',s=100,zorder=10)
and this produces
I know with matplotlib i can zoom on a orthographic projection with something like that :
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection=ccrs.Orthographic(-40, 20)
ax.set_extent([-110, 30, -20, 65])
How can i do this with hvplot / Geoviews / Holoviews ? All exemples i have found don't zoom on this specific projection,
actual example :
import xarray as xr
import hvplot.pandas
import holoviews as hv
import geoviews.feature as gf
import cartopy.crs as ccrs
proj = ccrs.Orthographic(-40, 20)
lon_range = (-110, 30)
lat_range = (-20, 65)
ds = xr.open_mfdataset(liste_files, engine="netcdf4")
pd_times = ds.to_dataframe() # <-- i cannot plot points with xarray directly, don't know why
points = pd_times.hvplot.points(x="longitude", y="latitude", c="sat1", projection=proj)
points = hv.Overlay(aff)
layout = (gf.ocean
* points
* gf.land.options(scale="50m")
* gf.coastline.options(scale="50m")
* gf.rivers
* gf.lakes
).opts(
width=500,
projection=proj
)
Thanks
Founded : you need to add xlim and/or ylim in the argument of hvplot.
points = pd_times.hvplot.points(x="longitude", y="latitude", c="sat1", projection=proj, xlim=lon_range, ylim=lat_range)
I am using jupyter notebook and I want to draw histograms. When I do not use GUI it is okay and everything is shown correctly but when I use the Tkinter version of the code, all bars in histogram are shifted to left so the first bar is missing.(e.g: It should be 4 on a,3 on b,9 on c but it shows 3 on a,9 on b, where a,b and c are ticks)
this is the first code i do not use gui:
import Tkinter as tk
from Tkinter import*
import tkMessageBox
import tkFileDialog
import pandas as pd
import pyautogui
import os
from PIL import Image, ImageTk
from tkinter import ttk
import pylab as plt
from matplotlib.ticker import (MultipleLocator, FormatStrFormatter,
AutoMinorLocator)
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
select1=pd.DataFrame()
select2=pd.DataFrame()
year1=1396
year2=1395
select1=df.loc[(df['yearj']==year1)]
select2=df.loc[(df['yearj']==year2)]
x=select1['monthj'].values.tolist()
y=select2['monthj'].values.tolist()
plt.xlabel('month')
plt.ylabel('number of orders')
bins=[1,2,3,4,5,6,7,8,9,10,11,12,13]
axx=plt.subplot()
axx.xaxis.set_major_locator(MultipleLocator(1))
axx.xaxis.set_major_formatter(FormatStrFormatter('%d'))
plt.hist(y,bins,rwidth=0.8)
plt.hist(x,bins,rwidth=0.8, alpha=0.6)
and the output is:
enter image description here
and here is second code:
import pandas as pd
import numpy
import pylab as plt
from matplotlib.ticker import (MultipleLocator, FormatStrFormatter,
AutoMinorLocator)
def compare_months(df,hh):
compmon = tk.Toplevel(h
bins=[1,2,3,4,5,6,7,8,9,10,11,12,13]
select1=pd.DataFrame()
select2=pd.DataFrame()
year1=1396
year2=1395
select1=df.loc[(df['yearj']==year1)]
select2=df.loc[(df['yearj']==year2)]
xr=select1['monthj'].values.tolist()
yr=select2['monthj'].values.tolist()
xr.sort(key=int)
yr.sort(key=int)
f = Figure(figsize=(7,6), dpi=80)
f.add_axes([0.15, 0.15,0.8,0.7])
canvas = FigureCanvasTkAgg(f, master=compmon)
canvas.get_tk_widget().grid(row=4, column=5, rowspan=8)
p = f.gca()
p.set_xlabel('month', fontsize = 10)
p.set_ylabel('number of orders', fontsize = 10)
p.hist(yr,bins,rwidth=0.8)
p.hist(xr,bins,rwidth=0.8, alpha=0.6)
p.xaxis.set_major_formatter(FormatStrFormatter('%d'))
p.xaxis.set_major_locator(MultipleLocator(1))
but=Button(compmon, text="ok", command=compare_months(df,root))
but.grid(row=2,column=2)
and the output is:enter image description here
Why does this happen?