2017-09-13 6 views
1

matplotlibの中に描かれた次の行matplotlibの:例えば、私が持っているピクセル単位たLine2Dの高さ

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ピクセルの高さ(私が使用しているフォントで)では、テキストの高さがおよそ12ピクセルの高さのため、およそ8行のテキストに収まることができます。

ピクセルの行の高さに関する情報はどのように取得できますか?または、テキストをレイアウトするより良い方法はありますか?

Text next to a straight line

+0

。 – Har

+0

これは、特にスプラインではなく、直線のピクセルの場合です。 – Har

答えて

1

あなたがそのバウンディングボックスを使用することができ画素単位で行の高さを得るために。バウンディングボックスがキャンバスに描画されたラインのものであることを確認するには、まずキャンバスを描画する必要があります。次に、境界ボックスは.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

関連する問題