I am a bery beginner with plotly graphing library, that is definetely an awesome tool for vizualisation and plot beautiful maps.
On spyder 5, I am developping to plot a spatial heat map according to the pd.Dataframe that I have inferred from my raw data .
import plotly.io as pio
import plotly.express as px
#from plotly.offline import plot
import pandas as pd
from netCDF4 import Dataset, num2date
import numpy as np
import numpy.ma as ma
pio.renderers.default = "svg"
nc_filename = '20220809_dataset-sargassum.nc'
#%% Ouverture du fichier & extraction de variables
if __name__ == '__main__':
nc = Dataset(nc_filename, 'r')
latitude = nc.variables['latitude'][:]
longitude = nc.variables['longitude'][:]
fai = nc.variables['fai_anomaly_daily_mean']
fai_data = fai[:]
fill_value= fai._FillValue
time = nc.variables['time']
time = num2date(time[0], time.units)
#%% Construction du Dataframe
x, y = np.meshgrid(ma.getdata(longitude), ma.getdata(latitude))
x = x.flatten()
y = y.flatten()
fai = ma.getdata(fai).flatten()
FAI_df = pd.DataFrame({'latitude':y,
'longitude' : x,
'Fai_anomaly':fai})
FAI_df['Fai_anomaly'].replace(fill_value, np.nan, inplace=True)
FAI_df['Fai_anomaly'][FAI_df['Fai_anomaly'] < 0] = np.nan
min_FAI = FAI_df['Fai_anomaly'].min()
max_FAI = FAI_df['Fai_anomaly'].max()
fig = px.density_mapbox(FAI_df,
lat='latitude',
lon='longitude',
z ='Fai_anomaly',
hover_data={"Fai_anomaly":True},
color_continuous_scale='Turbo',
range_color=(min_FAI,max_FAI)
)
#fig.update_layout(mapbox_style="stamen-terrain")
fig.update_layout(mapbox_style="white-bg",
title =('FAI'))
fig.show()
Nevertheless, when time comes to plot , I am getting the image below with mapbox_style='white-bg'. But the worst is that I am getting mapbox_style='open-street-map/stamen-terrain/or whatever the error :
File "/home/barbiersa#ad.meteo.fr/.conda/envs/py38_spyder/lib/python3.8/site-packages/kaleido/scopes/plotly.py", line 161, in transform
raise ValueError(
ValueError: Transform failed with error code 525: Mapbox error.
May someone help me to understand what is happening, I do not really have a clue of why neither the tile nor the colorbar are not showing.
Related
I am trying to do a basic plot of the world map using Python and the Matplotlib library. However, when I plot the polygons the plot shows many straight lines that do not seem to be part of the polygon. I am relatively new at working with shapefiles but the code I'm using has worked for a previous shapefile I used, so I'm confused and wondering what might be missing in the code.
The code I'm using is:
import numpy as np
import pandas as pd
import shapefile as shp
import matplotlib.pyplot as plt
import seaborn as sns
import os
sns.set(style='whitegrid', palette='ocean', color_codes=True)
sns.mpl.rc('figure', figsize=(10,6))
sf = shp.Reader(shp_path)
def plot_map(sf, x_lim = None, y_lim = None, figsize = (11,9)):
'''
Plot map with lim coordinates
'''
plt.figure(figsize = figsize)
id=0
for shape in sf.shapeRecords():
x = [i[0] for i in shape.shape.points[:]]
y = [i[1] for i in shape.shape.points[:]]
plt.plot(x, y, 'k')
if (x_lim == None) & (y_lim == None):
x0 = np.mean(x)
y0 = np.mean(y)
plt.text(x0, y0, id, fontsize=10)
id = id+1
if (x_lim != None) & (y_lim != None):
plt.xlim(x_lim)
plt.ylim(y_lim)
plot_map(sf)
plt.show()
The following link shows resulting graph (I'm not allowed to post pictures yet?):
Any help is appreciated, thank you all!
pls use 'k.', or use scatter instead of plot
import numpy as np
import pandas as pd
import shapefile as shp
import matplotlib.pyplot as plt
import seaborn as sns
import os
sns.set(style='whitegrid', palette='ocean', color_codes=True)
sns.mpl.rc('figure', figsize=(10,6))
sf = shp.Reader(shp_path)
def plot_map(sf, x_lim = None, y_lim = None, figsize = (11,9)):
'''
Plot map with lim coordinates
'''
plt.figure(figsize = figsize)
id=0
for shape in sf.shapeRecords():
x = [i[0] for i in shape.shape.points[:]]
y = [i[1] for i in shape.shape.points[:]]
## change here
plt.plot(x, y, 'k.')
if (x_lim == None) & (y_lim == None):
x0 = np.mean(x)
y0 = np.mean(y)
plt.text(x0, y0, id, fontsize=10)
id = id+1
if (x_lim != None) & (y_lim != None):
plt.xlim(x_lim)
plt.ylim(y_lim)
plot_map(sf)
plt.show()
[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.
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()
I have a .csv file which contains some data where x, y, x1, y1 are the coordinate points, and p is the value. My below code is working very well for plotting, but when I am plotting the data, I am getting a background color like the purple color. I don't want any color in the background. I want the background will be Transparent. My ultimate goal is overlying this result over an image. I am new in Python. Any help will be highly appreciated.
Download link of the .csv file here or link-2 or link-3
I am getting below result
My Code
import matplotlib.pyplot as plt
from scipy import ndimage
import numpy as np
import pandas as pd
from skimage import transform
from PIL import Image
import cv2
x_dim=1200
y_dim=1200
# Read CSV
df = pd.read_csv("flower_feature.csv")
# Create numpy array of zeros os same size
array = np.zeros((x_dim, y_dim), dtype=np.uint8)
for index, row in df.iterrows():
x = np.int(row["x"])
y = np.int(row["y"])
x1 = np.int(row["x1"])
y1 = np.int(row["y1"])
p = row["p"]
array[x:x1,y:y1] = p
map = ndimage.filters.gaussian_filter(array, sigma=16)
plt.imshow(map)
plt.show()
As per Ghassen's suggestion I am getting below results. I am still not getting the transparent background.
When Alpha =0
When alpha =0.5
When alpha =1
try with this code :
import matplotlib.pyplot as plt
from scipy import ndimage
import numpy as np
import pandas as pd
x_dim=1200
y_dim=1200
# Read CSV
df = pd.read_csv("/home/rosafi/Downloads/flower_feature.csv")
# Create numpy array of zeros os same size
array = np.ones((x_dim, y_dim), dtype=np.uint8)
for index, row in df.iterrows():
x = np.int(row["x"])
y = np.int(row["y"])
x1 = np.int(row["x1"])
y1 = np.int(row["y1"])
p = row["p"]
array[x:x1,y:y1] = p
map = ndimage.filters.gaussian_filter(array, sigma=16)
map = np.ma.masked_where(map == 0, map)
plt.imshow(map)
plt.show()
output:
I solved this issue by masking out the values where values ==0. The code will be
from mpl_toolkits.axes_grid1 import make_axes_locatable
masked_data = np.ma.masked_where(map == 0, map)
I got some interesting user data from races. I know when the respecitve athletes planed to finish a race and I know when they actaully finished (next to some more stuff). The goal is to find out when the athletes come in late. I want to run a support vector machine for each athlete and plot the decision boundaries.
Here is what I do:
import numpy as np
import pandas as pd
from sklearn import svm
from mlxtend.plotting import plot_decision_regions
import matplotlib.pyplot as plt
# Create arbitrary dataset for example
df = pd.DataFrame({'User': np.random.random_integers(low=1, high=4, size=50),
'Planned_End': np.random.uniform(low=-5, high=5, size=50),
'Actual_End': np.random.uniform(low=-1, high=1, size=50),
'Late': np.random.random_integers(low=0, high=2, size=50)}
)
# Fit Support Vector Machine Classifier
X = df[['Planned_End', 'Actual_End']]
y = df['Late']
clf = svm.SVC(decision_function_shape='ovo')
for i, y in df['User']:
clf.fit(X, y)
ax = plt.subplot()
fig = plot_decision_regions(X=X, y=y, clf=clf, legend=2)
plt.title(lab)
plt.show()
I get the following error: TypeError: 'numpy.int64' object is not iterable - that is, I somehow can't loop through the column.
I guess it comes down to the numpy data format? How can I solve that?
try iteritems()
for i, y in df['User'].iteritems():
Your User Series contains numpy.int64 objects so you can only use:
for y in df['User']:
And you don't use i anywhere.
As for the rest of the code, this produces some solution, please edit accordingly:
import numpy as np
import pandas as pd
from sklearn import svm
from mlxtend.plotting import plot_decision_regions
import matplotlib.pyplot as plt
# Create arbitrary dataset for example
df = pd.DataFrame({'User': np.random.random_integers(low=1, high=4, size=50),
'Planned_End': np.random.uniform(low=-5, high=5, size=50),
'Actual_End': np.random.uniform(low=-1, high=1, size=50),
'Late': np.random.random_integers(low=0, high=2, size=50)}
)
# Fit Support Vector Machine Classifier
X = df[['Planned_End', 'Actual_End']].as_matrix()
y = df['Late']
clf = svm.SVC(decision_function_shape='ovo')
y = df['User'].values
clf.fit(X, y)
ax = plt.subplot()
fig = plot_decision_regions(X=X, y=y, clf=clf, legend=2)
plt.title('lab')
plt.show()