2016-10-19 4 views
0

matplotlib 플롯에 텍스트를 배치하려하지만 그래프의 위치에 상대적인 텍스트를 유지하려고합니다.matplotlib 텍스트를 그래프에 상대적으로 배치하는 방법

텍스트의 원하는 위치는 이미지가 나타내는 섹션의 중심에 있음을 알 수 있습니다 (이미지 참조).

현재이 값을 사용하고있는 두 개의 offset 값이 있습니다. 그러나이 값을 더 이상 적용하지 않는 x 범위를 변경하면 더 이상 적용되지 않습니다.

텍스트의 위치를 ​​지정하는 일반적인 방법을 사용하여 텍스트의 용도에 관계없이 텍스트가 중앙에 위치하고 현명한 위치에 배치되도록하고 싶습니다.

현명하게 위치를 정하면 나는 $ \ delta x $와 그것을 나타내는 수평선 사이에 간격이 있어야 함을 의미합니다. 그리고 틈 사이 $ \ 델타 y를 $ 내가 을 사용하고

enter image description here

코드

#!/usr/bin/env python 

import numpy as np 
from matplotlib import pyplot as plt 
import matplotlib 
plt.style.use('ggplot') 

matplotlib.rcParams['text.usetex'] = True 
matplotlib.rcParams['text.latex.unicode'] = True 

############################################################################### 

def f(x): 
    return x**3 

def tri(x1, x2, f): 
    """input of two x coordinates and function, create and label a triangle to 
    represent finding the gradient 
    """ 

    color = "green" 
    lw = 3 

    # Plot the triangle beneath the curve 
    plt.plot([x1, x2], [f(x1), f(x1)], color=color, linewidth=lw) 
    plt.plot([x2, x2], [f(x1), f(x2)], color=color, linewidth=lw) 

    fontSz = 45 

    # TODO: I'M NOT SURE HOW TO PLACE THE FONT SO THAT IF I CHANGE THE FUNCTION 
    # OR FONT SIZE THE FONT IS PLACED IN THE SAME POSITION RELATIVELY 

    offset1 = 0.5 # < < < These! 
    offset2 = 0.05 # < < < 

    dx_x_place = ((x1) + (x2))/2 
    dx_y_place = f(x1) - offset1 

    dy_x_place = x2 + offset2 
    dy_y_place = (f(x1) + f(x2))/2 

    # annotate delta x 
    plt.text(
     dx_x_place, 
     dx_y_place, 
     r'$\delta x$', 
     horizontalalignment='center', 
     verticalalignment='top', 
     fontsize=fontSz, 
     color='black' 
    ) 

    # Annotate delta y 
    plt.text(
     dy_x_place, 
     dy_y_place, 
     r'$\delta y$', 
     horizontalalignment='left', 
     verticalalignment='center', 
     fontsize=fontSz, 
     color='black' 
    ) 

############################################################################### 

# global variables 
X_DOMAIN = [-1,4] 
X_DENSITY = 300 
LINEWIDTH = 3 


x = np.linspace(X_DOMAIN[0], X_DOMAIN[1], X_DENSITY) 
y = f(x) 

# Just put some axis on the graph 
# http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.axvline 
plt.axhline(linewidth = 1, color="grey") 
plt.axvline(linewidth = 1, color="grey") 

# create triangle to represent delta x,y 
tri(2, 3, f) 

plt.plot(x, y, linewidth=LINEWIDTH) 
plt.show() 

시스템 그 $ \ 델타 X $

출력 같아야한다
$ lsb_release -a 
No LSB modules are available. 
Distributor ID: Ubuntu 
Description: Ubuntu 14.04.5 LTS 
Release: 14.04 
Codename: trusty 

사용중인 Python 버전

(210)
3.5.2 |Continuum Analytics, Inc.| (default, Jul 2 2016, 17:53:06) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] 

하기 matplotlib 버전

import matplotlib 
matplotlib.__version__ 
Out[37]: '1.5.1' 

답변

1

싶은 것은이되지 않은 데이터 좌표에 있지만 축 좌표 또는 표시 좌표 중 하나에서, 고정 된 오프셋 유지하는 것입니다 (즉, 픽셀). 변환 작업은 조금 번거로우므로 the transform documentation 또는 the second example here을 사용하는 것이 좋습니다. 그러나 나는 문서, 특히 inverted() -function이 도움이 될 것이라고 믿습니다. 워드 프로세서는 말한다 : 변환 데이터을 조정하는 방법이 문서에서 예제와 함께, 화면에서 당신을 데려 갈 것이다 작성하는 반전() 메서드를 사용할 수 있습니다

In [1]: inv = ax.transData.inverted() 
In [2]: inv.transform((335.175, 247.)) 
Out[3]: array([ 5., 0.]) 

이 당신이 X 얻을 수 있다는 것을 의미한다 데이터 좌표에서 오프셋은 inv.transform(10, 0)이며, 이는 array([xoffset_corresponding_to_10pixels, 0])을 반환해야합니다. y- 오프셋도 똑같이하십시오. 확대/축소 할 때마다 오프셋 값을 업데이트해야 할 것입니다 ... 이것은 완전한 대답은 아니지만 잘하면 시작하는 데 도움이된다는 것을 알고 있습니다.

관련 문제