fig = plt.gcf() #Gets the current figure
fig.set_size_inches(10,10, forward=True) # changes size of figure. Forward must equal True to make the change
This page demonstrates Python tips and tricks that I use in my everyday programming as an atmospheric science graduate student.
-Brian Blaylock
Wednesday, August 13, 2014
Tuesday, August 12, 2014
Thursday, August 7, 2014
advances in computing will benefit weather forecasts
news about advances in computing abilities is always exciting news fore weather forecasters. Check out this article...
http://www.engadget.com/2014/08/07/ibm-synapse-supercomputing-chip-mimics-human-brain/?ncid=txtlnkusaolp00000618
http://www.engadget.com/2014/08/07/ibm-synapse-supercomputing-chip-mimics-human-brain/?ncid=txtlnkusaolp00000618
Relative Maximun and MInimum
It's easy to find the max and min of an array, but sometimes you want to find all local max an mins.
From post here:
From post here:
import numpy as np from scipy.signal import argrelextrema x = np.random.random(12) # for local maxima argrelextrema(x, np.greater) # for local minima argrelextrema(x, np.less)
Produces>>> x array([ 0.56660112, 0.76309473, 0.69597908, 0.38260156, 0.24346445, 0.56021785, 0.24109326, 0.41884061, 0.35461957, 0.54398472, 0.59572658, 0.92377974]) >>> argrelextrema(x, np.greater) (array([1, 5, 7]),) >>> argrelextrema(x, np.less) (array([4, 6, 8]),)
Note, these are the indices of x that are local max/min. To get the values, try:>>> x[argrelextrema(x, np.greater)[0]]
Wednesday, July 30, 2014
change tick mark size
http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.tick_params
Example
# Create Figure
fig = plt.figure(1)
ax = fig.add_subplot(111)
#increase size of tick marks
ax.tick_params('both', length=20, width=2, which='major')
ax.tick_params('both', length=10, width=1, which='minor')
Example
# Create Figure
fig = plt.figure(1)
ax = fig.add_subplot(111)
#increase size of tick marks
ax.tick_params('both', length=20, width=2, which='major')
ax.tick_params('both', length=10, width=1, which='minor')
Tuesday, July 29, 2014
Python Accessing all the files in a directory
This is a handy link that gets file names from a directory:
http://stackoverflow.com/questions/18262293/python-open-every-file-in-a-folder
For example:
path = 'C://Users/person/Pictures' for filename in glob.glob(os.path.join(path,'*.jpg')):
print filename
results in:
C:\Users\Brian\Pictures\East.jpg
C:\Users\Brian\Pictures\North.jpg
C:\Users\Brian\Pictures\Rocketeer.jpg
C:\Users\Brian\Pictures\South.jpg
C:\Users\Brian\Pictures\WIN_20140711_105811_edited.jpg
etc.
http://stackoverflow.com/questions/18262293/python-open-every-file-in-a-folder
For example:
path = 'C://Users/person/Pictures' for filename in glob.glob(os.path.join(path,'*.jpg')):
print filename
results in:
C:\Users\Brian\Pictures\East.jpg
C:\Users\Brian\Pictures\North.jpg
C:\Users\Brian\Pictures\Rocketeer.jpg
C:\Users\Brian\Pictures\South.jpg
C:\Users\Brian\Pictures\WIN_20140711_105811_edited.jpg
etc.
Friday, July 11, 2014
Easy Legend
The easiest way to make a legend is to give the plot a label when you first make the plot.
Example:
plt.plot(times_utc,duchesne, label="Duchesne")
plt.plot(times_utc,mtn_home, label="Mountain Home")
plt.plot(times_utc,horsepool, label="Horsepool")
plt.legend(loc=2)
Example:
plt.plot(times_utc,duchesne, label="Duchesne")
plt.plot(times_utc,mtn_home, label="Mountain Home")
plt.plot(times_utc,horsepool, label="Horsepool")
plt.legend(loc=2)
Thursday, July 3, 2014
Managing DateTime Tick Marks
When creating plots, one issue I continue to face is managing the tick marks. Customizing DateTime ticks is especially difficult. But I think I've found the best way to manage this problem.
When making a plot with a DateTime array on the x-axis, use this:
#Import packages
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, YearLocator, MonthLocator, DayLocator, HourLocator
# Create the plot
ax = plt.subplot(1,1,1)
plt.(datetime_array, y_variable)
# Format Ticks
# Find months
months = MonthLocator()
# Find days
days = DayLocator()
# Find each 0 and 12 hours
hours = HourLocator(byhour=[0,12])
# Find all hours
hours_each = HourLocator()
# Tick label format style
dateFmt = DateFormatter('%d:%H')
# Set the x-axis major tick marks
ax.xaxis.set_major_locator(hours)
# Set the x-axis labels
ax.xaxis.set_major_formatter(dateFmt)
# For additional, unlabeled ticks, set x-axis minor axis
ax.xaxis.set_minor_locator(hours_each)
Example Result:
A major tick mark every 0 and 12 hour with the label formatted as [Day:Hour]. A minor tick mark on every hour.
When making a plot with a DateTime array on the x-axis, use this:
#Import packages
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, YearLocator, MonthLocator, DayLocator, HourLocator
# Create the plot
ax = plt.subplot(1,1,1)
plt.(datetime_array, y_variable)
# Format Ticks
# Find months
months = MonthLocator()
# Find days
days = DayLocator()
# Find each 0 and 12 hours
hours = HourLocator(byhour=[0,12])
# Find all hours
hours_each = HourLocator()
# Tick label format style
dateFmt = DateFormatter('%d:%H')
# Set the x-axis major tick marks
ax.xaxis.set_major_locator(hours)
# Set the x-axis labels
ax.xaxis.set_major_formatter(dateFmt)
# For additional, unlabeled ticks, set x-axis minor axis
ax.xaxis.set_minor_locator(hours_each)
Example Result:
A major tick mark every 0 and 12 hour with the label formatted as [Day:Hour]. A minor tick mark on every hour.
Wednesday, May 7, 2014
Plotting Ceilometer data with imshow()
I have plotted a month of ceilometer data with matplotlib using imshow(). This figure shows backscatter at the mountain meteorology lab for January 2014.
Simple error catching
I always get stuck with errors when building scripts. Sometimes I want the program to do something even if there is an error. Here is an example of a simple way to catch errors:
try:
file = h5py.File(file.h5, 'r')
print 'Yes, this file exists'
except:
print 'Didn't work'
sys.exit()
Here I try to open the HDF5 file called 'file.h5'. If the file exists we print "Yes, this file exists."
If there is an error when the computer tries to open the file--for example, the file can not be found--then we print "Didn't work" and the python program closes.
try:
file = h5py.File(file.h5, 'r')
print 'Yes, this file exists'
except:
print 'Didn't work'
sys.exit()
Here I try to open the HDF5 file called 'file.h5'. If the file exists we print "Yes, this file exists."
If there is an error when the computer tries to open the file--for example, the file can not be found--then we print "Didn't work" and the python program closes.
Save matplotlib figures and save to a server
On my personal computer I have created many figures with matplotlib. I've always used plt.show() to show the figures and plt.savefig() to save the images, but I've had a lot of trouble saving a figure onto the server.
At work, python is installed on the server, but saving the figures has never worked. I always get the error no display name and no $DISPLAY environment variable
Turns out I was just missing a single line of code. After importing matplotlib type mpl.use('Agg'). This will fix the problem.
Example:
import matplotlib as mpl
mpl.use('Agg') #Not sure why, but this makes saving to a server possible.
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,50,.2)
y = np.sin(x)
plt.plot(x,y)
plt.title("This works!!! I'm so excited")
plt.savefig(path to save image + image_name.png)
plt.close()
Results in:
At work, python is installed on the server, but saving the figures has never worked. I always get the error no display name and no $DISPLAY environment variable
Turns out I was just missing a single line of code. After importing matplotlib type mpl.use('Agg'). This will fix the problem.
Example:
import matplotlib as mpl
mpl.use('Agg') #Not sure why, but this makes saving to a server possible.
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,50,.2)
y = np.sin(x)
plt.plot(x,y)
plt.title("This works!!! I'm so excited")
plt.savefig(path to save image + image_name.png)
plt.close()
Results in:
Monday, April 28, 2014
Downloads
Where can you download Python and Python packages???
Python is distributed through Enthought Canopy.
Packages can be downloaded through Surgeforce, the package website, and I also found this website that has a lot of packages in one place: http://www.lfd.uci.edu/~gohlke/pythonlibs/
Python is distributed through Enthought Canopy.
Packages can be downloaded through Surgeforce, the package website, and I also found this website that has a lot of packages in one place: http://www.lfd.uci.edu/~gohlke/pythonlibs/
Subscribe to:
Posts (Atom)