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

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')


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.

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)


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.