The goal for my code is to make a rough roadmap using the latitude and longitude of the exits on the pennsylvania turnpike drawing a line between each exit.
I am using a for loop to plot a line on the map every time it loops. This works if i hard code the latitude and longitude but as soon as i plug in my variables nothing gets plotted. Since the coordinates are in order I am just increasing the index every time it loops to get the next coordinates. I have printed the variables inside the loop and verified they have the desired value. I have tried putting the values in ordered pairs but the plot function didn't like me using nparrays. I'm not sure if there is something simple i am missing, but I appreciate any input.
import netCDF4 as nc
import numpy as np
import matplotlib.pyplot as plt
import cartopy
import cartopy.crs as ccrs
from datetime import datetime, timedelta
# Open the file for highway metadata to read csv data
highway_metadata = open('milestone3data.csv', 'r')
metafile = csv.reader(highway_metadata, delimiter = ',')
# Create empty lists with highway data
highway_loc = []
highway_name = []
highway_lat = []
highway_lon = []
highway_dist = []
# Loop to transfer the csv file's data into the lists
for i in metafile:
highway_loc.append(i[0])
highway_name.append(i[1])
highway_lat.append(float(i[2]))
highway_lon.append(float(i[3]))
highway_dist.append(i[4])
def road_map():
enhighway_lat = enumerate(highway_lat)
enhighway_lon = enumerate(highway_lon)
orthographic = ccrs.Orthographic()
platecarree = ccrs.PlateCarree()
proj = ccrs.Orthographic(central_longitude = -75, central_latitude = 41)
ax = plt.axes(projection=proj)
# Set up the background
ax.add_feature(cartopy.feature.COASTLINE)
ax.add_feature(cartopy.feature.STATES)
ax.set_extent((-85,-70,36,45),crs=ccrs.PlateCarree())
for i,j in enhighway_lat:
for k,l in enhighway_lon:
if i or k <= 30:
plt.plot([highway_lon[k], highway_lon[k+1]], [highway_lat[i], highway_lat[i+1]], color='black', linewidth=1, marker='o', markersize=3, transform=ccrs.PlateCarree())
plt.savefig('cartopytest7.png')
plt.show
road_map()
[This is my most recent output from the program][1]
[1]: https://i.stack.imgur.com/lgFrN.png
CSV file contents: (mile marker, name of exit, latitude, longitude, miles from beginning of turnpike)
2,Gateway (Ohio Connection),40.90419167,-80.47158333,1.43
10,New Castle,40.83018056,-80.34196111,10.7
13,Beaver Valley,40.8143,-80.307925,12.87
28,Cranberry,40.67983889,-80.09537778,28.47
30,Warrendale,40.65533889,-80.06116667,31
39,Butler Valley,40.60913611,-79.91924444,39.1
48,Allegheny Valley,40.542025,-79.81022222,47.73
57,Pittsburgh,40.43808889,-79.74956944,56.44
67,Irwin,40.31342778,-79.65476111,67.22
75,New Stanton,40.22173333,-79.59573333,75.39
91,Donegal,40.10915,-79.35231944,90.69
110,Somerset,40.02033056,-79.05208056,109.91
146,Bedford,40.05013889,-78.48615,145.5
161,Breezewood,39.98721667,-78.24472778,161.5
180,Fort Littleton,40.05010556,-77.93954444,179.44
189,Willow Hill,40.09674167,-77.78441389,188.59
201,Blue Mountain,40.15755278,-77.58403333,201.29
226,Carlisle,40.22814722,-77.14782222,226.54
236,Gettysburg Pike,40.19569444,-76.95665556,236.22
242,Harrisburg West Shore,40.21216667,-76.85765278,241.87
247,Harrisburg East,40.21501111,-76.78060278,247.38
266,Lebanon-Lancaster,40.22974444,-76.43095,266.45
286,Reading,40.21805,-76.05189167,286.09
298,Morgantown,40.15990278,-75.88311667,298.33
312,Downingtown,40.06838611,-75.66450278,311.93
320,SR29,40.07641667,-75.52881944,319.33
326,Valley Forge,40.09296667,-75.39591111,326.62
333,Norristown,40.11101111,-75.27921389,333.28
339,Fort Washington,40.13231944,-75.17092222,338.36
340,Virginia Dr,40.13854444,-75.16268611,339.8
343,Willow Grove,40.16166111,-75.11271111,342.91
351,Bensalem,40.13200278,-74.96229444,351.49
352,Street Rd,40.13150833,-74.96445,351.89
353,Neshaminy Falls,40.12916667,-74.94150278,352.67
Okay, based on the discussion above, see below for a solution.
Notes:
Am using pandas DataFames to easily work with the .csv file. the names field is the column names.
Am not using orthographic projection at all.
Am iterating through the list of highway exits one exit at a time; at each index, am extracting the current and next exits' data - am sure there's a more 'pythonic' way to do this, but this is readable at least.
edit: the final index in the loop is length-1
Update: Thanks to #SimonWillerton, I've removed the loop.
import netCDF4 as nc
import numpy as np
import matplotlib.pyplot as plt
import cartopy
import cartopy.crs as ccrs
import pandas as pd
def road_map():
# Open the file for highway metadata to read csv data
highway_metadata = pd.read_csv('milestone3data.csv', names=["loc", "name", "lat", "lon", "dist"])
proj = ccrs.PlateCarree(central_longitude = -75)
ax = plt.axes(projection=proj)
ax.add_feature(cartopy.feature.COASTLINE)
ax.add_feature(cartopy.feature.STATES)
ax.set_extent((-85,-70,36,45),crs=ccrs.PlateCarree())
plt.plot(highway_metadata['lon'], highway_metadata['lat'], \
color='black', linewidth=1, marker='o', markersize=3, transform=ccrs.PlateCarree())
plt.savefig('cartopytest7.png')
if __name__ == '__main__':
road_map()
This produces the following image:
And, based on this image of the Pennsylvania Turnpike from Wikipedia (source=https://commons.wikimedia.org/wiki/File:Pennsylvania_Turnpike_map.svg#file) I think we have success
It looked like you were trying to do something rather complicated with your plt.plot() statement. You have the list of longitudes and the list of lattitudes; that's all you need for plotting between the points in matplotlib, there's no need for enumerate or looping over lists. The following line should do the trick.
plt.plot(highway_lon, highway_lat, color='black', linewidth=1, marker='o', markersize=3, transform=ccrs.PlateCarree())
Here's the code with some unecessary bits removed.
import csv
import numpy as np
import matplotlib.pyplot as plt
import cartopy
import cartopy.crs as ccrs
# Open the file for highway metadata to read csv data
highway_metadata = open('milestone3data.csv', 'r')
metafile = csv.reader(highway_metadata, delimiter = ',')
# Create empty lists with highway data
highway_loc = []
highway_name = []
highway_lat = []
highway_lon = []
highway_dist = []
# Loop to transfer the csv file's data into the lists
for i in metafile:
highway_loc.append(i[0])
highway_name.append(i[1])
highway_lat.append(float(i[2]))
highway_lon.append(float(i[3]))
highway_dist.append(i[4])
def road_map():
fig = plt.figure(figsize=(10, 10))
proj = ccrs.Orthographic(central_longitude = -75,
central_latitude = 41)
ax = plt.axes(projection=proj)
ax.set_extent((-85,-70,36,45),crs=ccrs.PlateCarree())
# Set up the background
ax.add_feature(cartopy.feature.COASTLINE)
ax.add_feature(cartopy.feature.STATES)
plt.plot(highway_lon, highway_lat,
color='black', linewidth=1, marker='o', markersize=3,
transform=ccrs.PlateCarree())
plt.savefig('cartopytest7.png')
plt.show
road_map()
Good evening all, I'm really struggling with my code. I've made a 1D spectrum from a fits file. I've extracted the numerical values for each point along the file, but there are vertical lines of overexposed pixel values. I want to replace all values above 3000 with 0. This is what I've done so far:
import astropy as ap
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from astropy.io import fits
from pathlib import Path
from astropy.nddata import CCDData
from ccdproc import ImageFileCollection
import ccdproc as ccdp
from os import listdir, walk
import astropy.units as u
# this function converts the class astropy.io.fits.hdulist.HDUList to a numpy array as ccd data
fitsfile = fits.open("img/HLXSpectrum.fits")
def spec(fitsfile):
specList = fits.open("img/HLXSpectrum.fits", include_path=True)
imgList = []
for img in specList:
ccd = CCDData(fitsfile[0].data, unit="adu")
HLX = ccdp.trim_image(ccd, fits_section="[:2050, 480:840]")
imgList.append(ccd)
fitsfile.close()
specImg = CCDData(ccd, unit="adu")
return specImg
specImg = spec(fitsfile)
skyarray1 = specImg[180:220, 50:2045]
spectrum1 = np.array(skyarray1)
skyarray2 = specImg[220:260, 50:2045]
spectrum2 = np.array(skyarray2)
skyarray3 = specImg[140:180, 50:2045]
spectrum3 = np.array(skyarray3)
spectrumA = spectrum2 - spectrum3
spectrum = spectrumA - spectrum1
flux = []
pixel = []
fix = np.where(spectrum > 3000, spectrum, 0)
for i in range(len(fix[1])): # cropped img in x dimension
flux.append(np.sum(skyarray1[:, i]))
pixel.append(i)
plt.figure(figsize=(20, 16), dpi=800)
plt.plot(pixel, flux, color="red")
fig1 = plt.gcf()
plt.show()
# fig1.savefig("flux.png", dpi=800)
but no matter what I do, the image stays the same, even though the values in the arrays change. Why?
The problem comes down to what you're plotting here:
fix = np.where(spectrum > 3000, spectrum, 0)
for i in range(len(fix[1])): # cropped img in x dimension
flux.append(np.sum(skyarray1[:, i]))
pixel.append(i)
plt.figure(figsize=(20, 16), dpi=800)
plt.plot(pixel, flux, color="red")
fig1 = plt.gcf()
plt.show()
You're plotting flux, which is taking values from skyarray1, which has not been modified. I think you want to replace it with fix like this:
for i in range(len(fix[1])): # cropped img in x dimension
flux.append(np.sum(fix[:, i]))
pixel.append(i)
I am producing the probability distribution function of my variable, which is temperature:
and I am going to produce several plots with temperature PDF evolution.
For this reason, I would like to link the color of the plot (rainbow-style) with the value of the peak of the temperature distribution.
In this way, it is easy to associate the average value of the temperature just by looking at the color.
Here's the code I have written for producing plots of the PDF evolution:
from netCDF4 import Dataset
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import seaborn as sns
from scipy.stats import gaussian_kde
my_file = 'tas/tas.nc'
fh = Dataset(my_file, mode='r')
lons = (fh.variables['rlon'][:])
lats = (fh.variables['rlat'][:])
t = (fh.variables['tas'][:])-273
step = len(t[:,0,0])
t_units = fh.variables['tas'].units
fh.close()
len_lon = len(t[0,0,:])
len_lat = len(t[0,:,0])
len_tot = len_lat*len_lon
temperature = np.zeros(len_tot)
for i in range(step):
temperature=t[i,:,:]
temperature_array = temperature.ravel()
density = gaussian_kde(temperature_array)
xs = np.linspace(-80,50,200)
density.covariance_factor = lambda : .25
density._compute_covariance()
plt.title(str(1999+i))
plt.xlabel("Temperature (C)")
plt.ylabel("Frequency")
plt.plot(xs,density(xs))
plt.savefig('temp_'+str(i))
Because the question is lacking a working snippet, I had to come up with some sample data. This creates three datasets, where each one is colored with a specific color between blue (cold) and red (hot) according to their maximum value.
import matplotlib.pyplot as plt
import random
from colour import Color
nrange = 20
mydata1 = random.sample(range(nrange), 3)
mydata2 = random.sample(range(nrange), 3)
mydata3 = random.sample(range(nrange), 3)
colorlist = list(Color('blue').range_to(Color('red'), nrange))
# print(mydata1) print(mydata2) print(mydata3)
plt.plot(mydata1, color='{}'.format(colorlist[max(mydata1)]))
plt.plot(mydata2, color='{}'.format(colorlist[max(mydata2)]))
plt.plot(mydata3, color='{}'.format(colorlist[max(mydata3)]))
plt.show()
I have two lists of float values, one for time and other for voltage values taken from an oscilloscope (I assume). I have to draw an amplitude spectrum plot, but i'm not exactly sure what function I need to use and what parameters I need to give it, I tried fft(u), but it didn't work.
Any help is appreciated, let me know if you need more info.
Use numpy.
As an example, let me show how I analysed the frequencies in a stereo WAV file;
First I read the data and separated it in the left and right channels;
import wave
import numpy as np
wr = wave.open('input.wav', 'r')
sz = 44100 # Read and process 1 second at a time.
da = np.fromstring(wr.readframes(sz), dtype=np.int16)
left, right = da[0::2], da[1::2]
Next I run a discrete fourier transform on it;
lf, rf = abs(np.fft.rfft(left)), abs(np.fft.rfft(right))
And we plot the left channel with mathplotlib;
import matplotlib.pyplot as plt
plt.figure(1)
a = plt.subplot(211)
r = 2**16/2
a.set_ylim([-r, r])
a.set_xlabel('time [s]')
a.set_ylabel('sample value [-]')
x = np.arange(44100)/44100
plt.plot(x, left)
b = plt.subplot(212)
b.set_xscale('log')
b.set_xlabel('frequency [Hz]')
b.set_ylabel('|amplitude|')
plt.plot(lf)
plt.savefig('sample-graph.png')
The graph looks something like this;
Here is the Frequency-Time spectrum of the signal, stored in the wave file
import wave
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
signal_wave = wave.open('voice.wav', 'r')
sample_frequency = 16000
data = np.fromstring(signal_wave.readframes(sample_frequency), dtype=np.int16)
sig = signal_wave.readframes(-1)
sig = np.fromstring(sig, 'Int16')
For the wave file
sig = sig[:]
For some segment of the wave file
sig = sig[25000:32000]
To plot spectrum of the signal wave file
plt.figure(1)
c = plt.subplot(211)
Pxx, freqs, bins, im = c.specgram(sig, NFFT=1024, Fs=16000, noverlap=900)
c.set_xlabel('Time')
c.set_ylabel('Frequency')
plt.show()