matplotlib transform data units to pixel units code example

Example: matplotlib transform data units to pixel units

import matplotlib.pyplot as plt

# set up a figure
fig = plt.figure()
ax = fig.add_subplot(111)
x = np.arange(0, 10, 0.005)
y = np.exp(-x/2.) * np.sin(2*np.pi*x)
ax.plot(x,y)

# what's one vertical unit & one horizontal unit in pixels?
ax.transData.transform([(0,1),(1,0)])-ax.transData.transform((0,0))
# Returns:
# array([[   0.,  384.],   <-- one y unit is 384 pixels (on my computer)
#        [ 496.,    0.]])  <-- one x unit is 496 pixels.

Tags:

Misc Example