如何在matplotlib中以像素获取坐标轴上单个单位的长度?
我想把 markersize
设置为一个单位的高度。看起来 markersize
是以像素为单位的。那么,我该怎么知道“1个单位”(在某个轴上)有多少像素呢?
1 个回答
13
可以看看这个变换教程(哇,这个找起来可真不容易!)
特别是,axes.transData.transform(points)
这个函数会返回像素坐标,其中 (0,0) 是视口的左下角。
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.
你还可以进行各种其他的变换——比如相对于你的数据、相对于坐标轴、作为图形的比例,或者以像素为单位的图形(变换教程讲得非常好)。
如果想在像素和点(一个点是1/72英寸)之间转换,你可以试试 matplotlib.transforms.ScaledTransform
和 fig.dpi_scale_trans
(我记得教程里有提到这个)。