[AstroPy] matplotlib histograms and astropy quantites

John K. Parejko parejkoj at uw.edu
Wed Jul 27 05:00:59 EDT 2016


I wonder if I'm misusing astropy quantities, or if there's a bug with how it interacts with matplotlib's pyplot.hist (and thus np.histogram). I've attached a minimal working example that represents a histogram I was attempting to create. If you try to make the plot range be a unit, plt.hist will fail. I would have thought that I could specify a range with units and get the plot axis to match the units I want to show the data with.

Also, trying to draw a vertical line with axvline() on a Quantity fails, though I guess I shouldn't be surprised at that. But given the above, this was also surprising to me.

I feel like there could be some more documentation about the interaction between astropy quantities and matplotlib?

Am I missing something here?

Thanks in advance,
John


import numpy as np
from astropy import units as u
import matplotlib.pyplot as plt

range1 = (-3, 3)
range2 = range1*u.arcsecond
np.random.seed(100)
data = np.random.normal(scale=3e-6, size=100)*u.radian
plt.figure()
# Not well centered and wrong X scale.
plt.hist(data)
# Works: I guess I shouldn't be surprised that I have to extract a value here.
plt.axvline(x=data[0].value, color='red')
plt.figure()
# Wanted the range in arcseconds, so this isn't right!
plt.hist(data, range=range1)
# Dimensionalizing it seems to work correctly.
plt.axvline(x=data[0]/u.arcsecond, color='red')
plt.figure()
# UnitsError: Can only apply 'less_equal' function to dimensionless quantities...
plt.hist(data, range=range2)
# UnitsError: Can only apply 'greater' function to dimensionless quantities...
plt.axvline(x=data[0])






More information about the AstroPy mailing list