aresnick
aresnick

Reputation: 1635

How can I get the length of a single unit on an axis in matplotlib, in pixels?

I want to make markersize equal to a single unit in height. It seems that markersize is in pixels. How can I get at how large "1 unit" (along a given axis) is, in pixels?

Upvotes: 11

Views: 4292

Answers (1)

mathematical.coffee
mathematical.coffee

Reputation: 56905

Have a look at the Transformations tutorial (wow, that took a lot of digging to find -- !)

In particular, axes.transData.transform(points) returns pixel coordinates where (0,0) is the bottom-left of the viewport.

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.

There are various other transforms you can do -- coordinates relative to your data, relative to the axes, as a proportion of the figure, or in pixels for the figure (the transformations tutorial is really good).

TO convert between pixels and points (a point is 1/72 inches), you may be able to play around with matplotlib.transforms.ScaledTransform and fig.dpi_scale_trans (the tutorial has something on this, I think).

Upvotes: 13

Related Questions