Matplotlib:以像素为单位

问题描述:

的Line2D高度我有例如下面的行matplotlib绘制Matplotlib:以像素为单位

import matplotlib.pyplot as plt 
fig = plt.figure() 
ax = fig.add_subplot(2,1,1) # two rows, one column, first plot 
# This should be a straight line which spans the y axis 
# from 0 to 50 
line, = ax.plot([0]*50, range(50), color='blue', lw=2) 
line2, = ax.plot([10]*100, range(100), color='blue', lw=2) 

我怎么能得到多少像素是直线,在y方向?

注意:我有几条这些线之间存在空隙,我想将文本放在它们旁边,但是,如果线条太多,我需要知道可以添加多少文本,即我需要线条的高度的原因。

例如在附图中,右侧有一条蓝线,高度约为160像素。在160像素的高度(使用我使用的字体)时,我可以放入大约8行文字,因为文字高度大约为12像素高。

如何获取有关线条像素高度的信息?还是有更好的方法来摆脱文字?

Text next to a straight line

+0

感谢您的评论就行了。 – Har

+0

这是专门针对直线的像素,而不是样条线。 – Har

为了获得以像素为单位,您可以使用其边框的单位线的高度。为确保边界框是画布上绘制的线条的边框,首先需要绘制画布。然后通过.line2.get_window_extent()获得边界框。边界框上端(y1)与下端(y0)之间的差异就是您要查找的像素数。

fig.canvas.draw() 
bbox = line2.get_window_extent(fig.canvas.get_renderer()) 
# at this point you can get the line height: 
print "Lineheight in pixels: ", bbox.y1 - bbox.y0 

为了在该行的y范围内绘制文本,以下内容可能会有用。给定点的字体大小,例如fontsize = 12,您可以计算像素的大小,然后计算可能的文本行数以适合上面确定的像素范围。使用混合变换,其中x以数据单位为单位,y以像素为单位允许您以数据单位(此处为x=8)指定x坐标,但以直线的范围计算坐标中的y坐标(以像素为单位)。

import matplotlib.pyplot as plt 
import matplotlib.transforms as transforms 

fig = plt.figure() 
ax = fig.add_subplot(2,1,1) 

line, = ax.plot([0]*50, range(50), color='blue', lw=2) 
line2, = ax.plot([10]*100, range(100), color='blue', lw=2) 

fig.canvas.draw() 
bbox = line2.get_window_extent(fig.canvas.get_renderer()) 
# at this point you can get the line height: 
print "Lineheight in pixels: ", bbox.y1 - bbox.y0 

#To draw text 
fontsize=12 #pt 
# fontsize in pixels: 
fs_pixels = fontsize*fig.dpi/72. 
#number of possible texts to draw: 
n = (bbox.y1 - bbox.y0)/fs_pixels 
# create transformation where x is in data units and y in pixels 
trans = transforms.blended_transform_factory(ax.transData, transforms.IdentityTransform()) 
for i in range(int(n)): 
    ax.text(8.,bbox.y0+(i+1)*fs_pixels, "Text", va="top", transform=trans) 


plt.show() 

enter image description here