I'm trying to plot contours of ash deposit depth using Basemap and matplotlib. For some reason, my contours aren't showing up and I can't see what I'm missing.
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from netCDF4 import Dataset
from mpl_toolkits.basemap import Basemap
url = "BigAsh_DepoThick.nc"
data = Dataset(url, mode="r")
times = data.variables["time"]
lats = data.variables["Lat"][:]
lons = data.variables["Lon"][:]
depths = data.variables["DepoThick"][:,:,:]
fig=plt.figure(figsize=(16,8))
# Create the map
m = Basemap(llcrnrlon=-150,llcrnrlat=10,urcrnrlon=-60,urcrnrlat=70,
projection='merc', resolution ='l')
m.drawcoastlines(linewidth=1)
m.drawstates(linewidth=1)
m.drawcountries(linewidth=1)
m.fillcontinents(color='gray')
plons, plats = np.meshgrid(lons, lats)
x, y = m(plons, plats)
cp = m.contourf(x, y, depths[-1,:,:], 100)
cbar = plt.colorbar(cp)
cbar.set_label("Ash Depth [mm]")
plt.title("Mt. St. Helens Ash Depth")
plt.show()
Related
I have plotted the contour of some data from file, but I need to generate a file with the coordinates of this contour. My code is the following:
import os
import sys
import pandas as pd
import numpy as np
from descartes import PolygonPatch
import matplotlib.pyplot as plt
sys.path.insert(0, os.path.dirname(os.getcwd()))
import alphashape
data1 = pd.read_csv('SDSS_19.txt', sep='\s+', header=None)
data1 = pd.DataFrame(data1)
x = data1[0]
y = data1[1]
points = np.vstack((x, y)).T
fig, ax = plt.subplots(figsize=(20,20))
ax.scatter(x, y, alpha=0.5, color='red')
alpha_shape = alphashape.alphashape(points, 0.6)
ax.add_patch(PolygonPatch(alpha_shape, alpha=0.25))
plt.savefig('contour.png')
plt.show()
The output is the following:
What I need is to calculate the coordinates of some points (the more the best) of the black line (the contour).
any help? Thanks.
I am using Basemap with a 3D graph to display ray paths. I would like to implement one of basemap's topo, shaded relief or bluemarble layers but I am running into the same issue over and over again:
NotImplementedError: It is not currently possible to manually set the aspect on 3D axes
I have already implemented fixed_aspect=False into calling the basemap
and have also tried ax.set_aspect('equal') which gives me the same error
I am using matplotlib ==2.2.3
Here is my code:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.basemap import Basemap
import numpy as np
from io import StringIO
import re
f = open("best-working4D.ray_paths", 'r') #125 waves - 125 "lines"
data = f.read()
lines = data.split('\n ')
fig = plt.figure()
ax = plt.axes(projection='3d')
extent = [300, 360, 50, 75]
bm = Basemap(llcrnrlon=extent[0], llcrnrlat=extent[2],
urcrnrlon=extent[1], urcrnrlat=extent[3], resolution='l', fix_aspect= False)
bm.bluemarble()
for i in range(1, 119):
wave = lines[i]
j = wave.split('\n')
k = []
for i in j:
k.append(i.split())
x=[]
y=[]
z=[]
n= 0
for m in k[1:]:
x.append(m[0])
y.append(m[1])
z.append(m[2])
x= np.array(x).astype('float32')
y= np.array(y).astype('float32')
z= np.array(z).astype('float32')
ax.plot3D(x,y,z, color='red')
##Plotting Tropopause
T_hi = 20
xx, yy = np.meshgrid(range(300,360), range(50,75))
zz = yy*0 + T_hi
ax.plot_surface(xx, yy, zz, alpha=0.15)
ax.set_xlabel("Latitude [deg]")
ax.set_ylabel("Longitude [deg]")
ax.set_zlabel("Altitude [km]")
ax.add_collection3d(bm.drawcoastlines(linewidth=0.25))
plt.show()
The basemap IS working for the bm.drawcoastlines just nothing else.
IMAGELINK
I would greatly appreciate any ideas!
I am having problems in making mollweide plots in the borders. The lines do not continue on the other side of the plot.
Is there any way to fix this (the green curve should continue in the other side of the sphere )? I am using matplotlib projections. The code is plotting circles of known radius and known center but matplotlib is just cutting the lines. How I could solve this?
import math
import numpy as np
import getdist.plots as plots
import matplotlib.pyplot as plt
import matplotlib.ticker
import matplotlib
import scipy
import pandas as pd
from scipy.stats import norm
from matplotlib import rc
from getdist import loadMCSamples
from getdist import loadMCSamples
from getdist import covmat
from getdist import MCSamples
from tabulate import tabulate
from scipy.optimize import curve_fit
from matplotlib.projections.geo import GeoAxes
from mpl_toolkits.mplot3d import Axes3D
class ThetaFormatterShiftPi(GeoAxes.ThetaFormatter):
"""Shifts labelling by pi
Shifts labelling from -180,180 to 0-360"""
def __call__(self, x, pos=None):
if x != 0:
x *= -1
if x < 0:
x += 2*np.pi
return GeoAxes.ThetaFormatter.__call__(self, x, pos)
mean1024 = [1,186,48]
sigma1024 = 30
x = np.linspace(-6.0, 6.0, 100)
y = np.linspace(-6.0, 6.0, 100)
X, Y = np.meshgrid(x,y)
l = (360.-mean1024[1])/(180/np.pi)
b = (mean1024[2])/(180/np.pi)
F = (X-l)**2 + (Y-b)**2 - (sigma1024/(180/np.pi))**2
F2 = (X-l)**2 + (Y-b)**2 - (2*sigma1024/(180/np.pi))**2
fig, axs = plt.subplots(figsize=(15,10))
axs = plt.subplot(projection="mollweide")
axs.set_longitude_grid(45)
axs.xaxis.set_major_formatter(ThetaFormatterShiftPi(45))
axs.set_latitude_grid(45)
axs.set_longitude_grid_ends(90)
plt.grid(True)
axs.contour(X,Y,F,[0], linewidths=1.5, colors = ['g'])
axs.contour(X,Y,F2,[0], linewidths=1.5, colors = ['g'])
plt.plot(l, b, '+', color = 'green')
box = axs.get_position()
axs.set_position([box.x0, box.y0, box.width * 0.8, box.height*0.8])
axs.legend(loc='lower right', bbox_to_anchor=(1.1, -0.2))
fig.savefig('circles.png')
plt.close()
I have a dataset looking like this:
1 38.7114 -7.92482 16.4375 0.2
...
I'd like to make a 3D scatter plot. I've done it using cartesian coordinates. How I can do it using geographic coordinates? Any hint?
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import sys
from mpl_toolkits.basemap import Basemap
ID=[]
Latitude=[]
Longitude=[]
Depth=[]
cluster1='data1'
with open(cluster1) as f:
lines = f.readlines()
for line in lines:
items = line.strip().split()
lat = float(items[1])
lon = float(items[2])
dep = float(items[3])
mag = float(items[4])
Latitude.append(lat)
Longitude.append(lon)
Depth.append(dep)
ID.append(mag)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
p = ax.scatter(Longitude, Latitude, Depth, c=ID, marker='o')
ax.set_xlabel('Longitude')
ax.set_ylabel('Latitude')
ax.set_zlabel('Depth (km)')
ax.invert_zaxis()
cb = fig.colorbar(p,label='Magnitude')
plt.savefig('plot1.png')
I had a question regarding Matplotlib and Basemap in python. I am trying to take a list of latitudes and longitudes and temperatures and plot them on a contour map. I had relative success when I put in data for Alaska. It plotted my data no problem. When I tried putting in data for Alabama, it outputted a completely random map filled with a bunch of garbage data points. I think this may be a problem with the map projection as I subbed out the Alaska data that gave me a working map for the Alabama data that gave me random data. It could be that the differences in coordinates are distorting the temperature values. I'm not exactly sure.
Thanks,
Scott
Here is an example of the Alabama data(first column:ICAO, second column: lat, third column: lon,4th column:temp):
K8A0,34.14,-86.15, 64
KALX,32.55,-85.58, 65
K79J,31.19,-86.24, 75
KANB,33.35,-85.51, 69
import urllib2
from urllib2 import urlopen
import cookielib
from cookielib import CookieJar
import time
from Tkinter import *
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 scipy import interpolate
import scipy
from matplotlib.colors import Normalize
FN = '/Users/scottreinhardt/Desktop/airportcodetext1.txt'
data = np.genfromtxt(FN,dtype=None,names=["ICAO","Lat","Lon","Temp"],skip_header=1,delimiter=',')
m = Basemap(projection = 'cyl',llcrnrlon = -73.5, llcrnrlat = 41, urcrnrlon = -81, urcrnrlat = 30, resolution='h')
# data from http://water.weather.gov/precip/
# create polar stereographic Basemap instance.
plt.figure(num=None, figsize=(25, 25), dpi=25,edgecolor='k')
xs = np.array(data["Lon"])
ys = np.array(data["Lat"])
z = np.array(data["Temp"])
#x = x + np.random.normal(scale=1e-8, size=x.shape)
#y = y + np.random.normal(scale=1e-8, size=y.shape)
#numcols, numrows = 300, 300
xi = np.linspace(data["Lat"].min(), data["Lat"].max(), 150)
yi = np.linspace(data["Lon"].min(), data["Lon"].max(), 150)
xi, yi = np.meshgrid(xi, yi)
# Set up a regular grid of interpolation points
#xi, yi = np.linspace(xs.min(), xs.max(), 500), np.linspace(ys.min(), ys.max(), 500)
#xi, yi = np.meshgrid(xi, yi)
# Interpolate
rbf = scipy.interpolate.Rbf(data["Lat"], data["Lon"], data["Temp"], function='linear')
zi = rbf(xi, yi)
plt.imshow(zi, vmin=z.min(), vmax=z.max(), origin='lower',
extent=[xs.min(), xs.max(), ys.min(), ys.max()])
plt.colorbar()
plt.show()