This page demonstrates Python tips and tricks that I use in my everyday programming as an atmospheric science graduate student.
-Brian Blaylock

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.

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: