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

Thursday, June 11, 2015

Python and MesoWest API

Uses the MesoWest API to get ozone concentration data and plot them. An example of formatting plot datetime plot tick marks is also shown.

# Brian Blaylock
# June 9, 2015

# Uses the MesoWest API to get find the maximum ozone
# from in-situ stations during GSLSO3S

# Tips for creating API request:
# -look at MesoWest API documentation: http://mesowest.org/api/docs/
# -use JSON viewer to see request results: http://jsonviewer.stack.hu/


import json
import numpy as np
import urllib2
import matplotlib.pyplot as plt
from datetime import datetime
from matplotlib.dates import DateFormatter, YearLocator, MonthLocator, DayLocator, HourLocator

token = '1234567890' #contact mesowest@lists.utah.edu to get your own token.

station = 'mtmet'
# dateformat YYYYMMDDHHMM
start_time = '201506050000'
end_time = '201506060000'
variables = 'ozone_concentration'
time_option = 'local'
URL = 'http://api.mesowest.net/v2/stations/timeseries?stid='+station+'&start='+start_time+'&end='+end_time+'&vars='+variables+'&obtimezone='+time_option+'&token='+token

#Open URL and read the content
f = urllib2.urlopen(URL)
data = f.read()

# convert that json string into some python readable format
data = json.loads(data)

stn_name = data['STATION'][0]['NAME']
# get ozone data convert to numpy array
ozone = data["STATION"][0]["OBSERVATIONS"]["ozone_concentration_set_1"]
#convert ozone into a numpy array: setting dtype=float replaces None value with a np.nan
ozone = np.array(ozone,dtype=float)

# get date and times and convert to datetime and put into a numpy array
dates = data["STATION"][0]["OBSERVATIONS"]["date_time"]
DATES = np.array([]) # first make an empty array
for i in dates:
   if time_option=='utc':
      converted_time = datetime.strptime(i,'%Y-%m-%dT%H:%M:%SZ')
   else:
      converted_time = datetime.strptime(i,'%Y-%m-%dT%H:%M:%S-0600')
   DATES = np.append(DATES,converted_time)


# make a simple ozone time series
#----------------------------------------------------------
ax = plt.subplot(1,1,1)
plt.plot(DATES,ozone)
plt.title('Ozone Concentration (ppb) for '+stn_name)
plt.xlabel('date')
plt.xticks(rotation=30)
#Now we format the date ticks
# Format Ticks
# Find months
months = MonthLocator()
# Find days
days = DayLocator()
# Find each 0 and 12 hours
hours = HourLocator(byhour=[0,6,12,18])
# Find all hours
hours_each = HourLocator()
# Tick label format style
dateFmt = DateFormatter('%b %d\n%H:%M')
# 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)


plt.savefig(start_time+'_'+end_time+'.png', format='png')




No comments:

Post a Comment

Note: Only a member of this blog may post a comment.