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

Friday, September 23, 2016

Python Matplotlib subscript

This is how to add subscripts to a string in your matlab plot
See more here: http://matplotlib.org/users/mathtext.html

plt.scatter(cyr_no80,co2_no80,color='k',marker='+',label='points')
plt.title(r'CO$_2$ Concentration, no 1980s')
plt.ylabel(r'CO$_2$ (ppm)')
plt.xlabel('Year')


Friday, September 9, 2016

Sorting multiple vectors based on one vector sort order

That title was a mouthful. First, I want to sort an array vector. Then I want to sort other vectors with that same sort order.

I have a vector that contain heights, and with that two other vectors with the corresponding temperature and dew point. I want to sort the height array, and sort the temperature and dew point array in the same manner.

height = np.array([10, 50, 20, 30, 60, 20, 80])
temp = np.array([1, 4, 2, 7, 5, 3, 9])
dwpt = np.array([6, 3, 8, 5, 7, 4, 6])

First, use np.argsort to get the sort order.

sort_order = np.argsort(height)

[out] array([0, 2, 5, 3, 1, 4, 6], dtype=int64)

Now make new arrays of the sorted data with that sort order

sorted_height = np.array(height)[sort_order]
[out] array([10, 20, 20, 30, 50, 60, 80])

sorted_temp = np.array(temp)[sort_order]
[out] array([1, 2, 3, 7, 4, 5, 9])

sorted_dwpt = np.array(dwpt)[sort_order]
[out] array([6, 8, 4, 5, 3, 7, 6])

Thus, you see that we have sorted the height array from lowest to highest, and the temperature and dew point arrays have been sorted, preserving their order with the corresponding height.