Develop wireframe to plot aircraft tracks with Lat, Lon and Alt - python

I am unable to draw a wireframe (not a map) with Lat, Lon and Alt.
My data looks like this:
latitude longitude altitude
0 53.65947 -1.43819 14525
1 53.65956 -1.43921 14525
2 53.65979 -1.44066 14500
3 53.66025 -1.44447 14475
4 53.66044 -1.44591 14475
Here is what I have so far:
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.animation as animation
df = pd.read_csv('/home/luke/Downloads /dump1090-127_0_0_1-170911.txt', sep=',',skiprows=0, low_memory=False)
y = df['latitude']
x = df['longitude']
z = df['altitude']
plt.xticks(range(-3,0))
plt.yticks(range(50,60))
ax = plt.axes(projection='3d')
df1 = df1.dropna()
Help would be greatly appreciated.

The reason your code is not plotting anything is that it isn't complete. You haven't included a plot command.
Suggest reading the documentation and looking at examples when you are trying to do something new.
In the example linked to above, you will see that the plot3D command is used to actually make the plot. If you add this to your code it should work.
ax.plot3D(x, y, z)
plt.show()
Also, note that a 3D wireframe plot is something different. I'm not sure it would be useful for plotting the path of an aeroplane.

Related

Why does adding a legend in this cartopy projection figure significantly increase the execution time (and how can fix this)?

So I have written a script for making figures that worked alright (see mock-up example below). But when I add a legend to the figure, the execution time increases a lot. I don't really understand what is happening here, I would naively expect that simply adding a legend is not a complex thing.
I suspect this has something to do with the cartopy projection, since it works alright if I don't use this.
What is the problem here, and how can I avoid this?
Problematic code:
import numpy as np
import xarray as xr
import matplotlib
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
# Mockup dataset
num = 300
lat = np.linspace(-54,-59,num=num)
lon = np.linspace(-5,5, num=num)
data = np.outer(lat,lon)
ds = xr.DataArray(data=data,
dims=["lat", "lon"],
coords=dict(lon=lon, lat=lat))
# Map projection
map_proj = ccrs.SouthPolarStereo()
ax = plt.axes(projection=map_proj)
ax.gridlines(draw_labels=True)
ax.set_extent([-3,4,-58,-54])
# Plot image
ds.plot(cmap="gray",
add_colorbar=False,
transform=ccrs.PlateCarree(), # data projection
subplot_kws={'projection': map_proj}) # map projection
# Plot contours
cs = ds.plot.contour(transform=ccrs.PlateCarree())
# Make legend
proxy = [matplotlib.lines.Line2D([],[], c=pc.get_color()[0]) for pc in cs.collections]
labels = ["foo"] * len(cs.collections)
plt.legend(proxy, labels)
Code without cartopy projection:
import numpy as np
import xarray as xr
import matplotlib
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
# Mockup dataset
num = 300
lat = np.linspace(-54,-59,num=num)
lon = np.linspace(-5,5, num=num)
data = np.outer(lat,lon)
ds = xr.DataArray(data=data,
dims=["lat", "lon"],
coords=dict(lon=lon, lat=lat))
# Plot image
ds.plot(cmap="gray",
add_colorbar=False) # map projection
# Plot contours
cs = ds.plot.contour()
# Make legend
proxy = [matplotlib.lines.Line2D([],[], c=pc.get_color()[0]) for pc in cs.collections]
plt.legend(proxy, labels)
plt.legend(proxy, labels) defaults to loc='best' which uses an algorithm that can be slow if you have lots of data in your axes, and particularly slow if that data also has complicated transforms. Instead do ax.legend(proxy, labels, loc='upper right') manually. See https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.legend.html

Displaying Colormap/legend with x,y,z plot and fourth variable

I'm using Pandas and am very new to programming. I'm plotting Energy Deposited (eDep) as a function of its x,y and z positions. So far, was successful in getting it to plot, but it won't let me plot the colormap beside my scatter plot! Any help is much appreciated
%matplotlib inline
import pandas as pd
import numpy as np
IncubatorBelow = "./Analysis.Test.csv"
df = pd.read_csv(IncubatorBelow, sep = ',', names['Name','TrackID','ParentID','xPos','yPos','zPos','eDep','DeltaE','Einit','EventID'],low_memory=False,error_bad_lines=False)
df["xPos"] = df["xPos"].str.replace("(","")
df["zPos"] = df["zPos"].str.replace(")","")
df.sort_values(by='Name', ascending=[False])
df.dropna(how='any',axis=0,subset=['Name','TrackID','ParentID','xPos','yPos','zPos','eDep','DeltaE','Einit','EventID'], inplace=True)
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
df['xPos'] = df['xPos'].astype(float)
df['yPos'] = df['yPos'].astype(float)
df['zPos'] = df['zPos'].astype(float)
#df10[df10['Name'].str.contains("e-")]
threedee = plt.figure().gca(projection='3d')
threedee.scatter(df["xPos"], df["yPos"], df["zPos"], c=df["eDep"], cmap=plt.cm.coolwarm)
threedee.set_xlabel("x(mm)")
threedee.set_ylabel("y(mm)")
threedee.set_zlabel("z(mm)")
plt.show()
Heres what the plot looks like!
Its from a particle physics simulation using GEANT4. The actual files are extremely large (3.7GB's that I've chunked into 40ish MB's) and this plot only represents a small fraction of the data.

matplotlib swap x and y axis

Hello I have made a plot in matplot lib using pandas however I need to swap my x and y axis.
Here is my plot:
broomstick plot
however i need it to look like this:
correct broomstick plot
I'm using a pandas dataframe to plot the data.
I've looked over some documentation and other posts regarding swapping the x and y axis and haven't found any easy way to do this.
Here some of my python code:
python code
Any resources or ideas would be greatly appreciated.
Try this. You need to include your y_vals as an additional column. So with this you can just specify your axis here df.plot(x=, y=):
Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 100)
y = np.cos(x)
df = pd.DataFrame({'y': y, 'x': x})
df.plot(x='x')
plt.show()
df.plot(x='y')
plt.show()
Plots:

Contour plot from csv file with row being axis

I am trying to make a contour plot from a csv file. I would like the first column to be the x axis, the first row (with has values) to be the y, and then the rest of the matrix is what should be contoured, see the basic example in the figure below.
Simple table example
What I am really struggling is to get that first row to be the y axis, and then how to define that set of values so that they can be called into the contourf function. Any help would be very much appreciated as I am very new to python and am really don't know where to start with this problem.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import csv
import pandas as pd
import numpy as np
from csv import reader
from matplotlib import cm
f = pd.read_csv('/trialforplot.csv',dayfirst=True,index_col=0)
x = f.head()
y = f.columns
X,Y = np.meshgrid(x,y)
z=(x,y)
z=np.array(z)
Z=z.reshape((len(x),len(y)))
plt.contour(Y,X,Z)
plt.colorbar=()
plt.xlabel('Time')
plt.ylable('Particle Size')
plt.show()
I'm stuck at defining the z values and getting my contour plot plotting.

Plotting NOAA data with Basemap

I'm very new to Python but have been learning lots over the last few months. I'm trying to plot NOAA swell height data from a grib2 file located here: ftp://ftpprd.ncep.noaa.gov/pub/data/nccf/com/wave/prod/wave.20140122/nww3.t06z.grib.grib2
I use Basemap and a tutorial that I found on a Basemap forum.
A minimum working example is below, but I'm getting some strange white boxes around the coastline.
import Nio
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
f = Nio.open_file('nww3.t12z.grib(2).grib2')
lons = f.variables['lon_0'][:]
lats = f.variables['lat_0'][::-1] # flip latitudes so data goes S-->N
times = f.variables['forecast_time0'][:]
ntime = 5
data = f.variables['HTSGW_P0_L1_GLL0'][ntime,::-1]
fig = plt.figure(figsize=(16,16))
m = Basemap(llcrnrlon=-35.,llcrnrlat=42.,urcrnrlon=5.,urcrnrlat=65.,
projection='lcc',lat_1=10.,lat_2=15.,lon_0=10.,
resolution ='h',area_thresh=1000.)
x, y = m(*np.meshgrid(lons, lats))
m.fillcontinents(color='#477519')
m.drawcoastlines(linewidth=0.5, color='k', antialiased=1, ax=None, zorder=None )
m.contourf(x, y, data, np.arange(0,9.9,0.1))
plt.show()
This is the result (the top panel; I would like it to look like the bottom panel): http://oi43.tinypic.com/s2s3m0.jpg
Sorry I don't have enough points to post images.
Thanks in advance,
Al

Categories

Resources