2014-06-08 2 views
13

파이썬으로 그림을 만들고 make는 동일한 annonate 텍스트가 두 가지 색상을 가지므로 annonate의 절반이 파란색이고 나머지 절반은 빨간색입니다.matplotlib 동일한 주석의 두 가지 다른 색상

코드 자체를 설명한다고 생각합니다. 나는 3 줄의 초록색 녹색 초록색 1 개, 파란색 1 개 파란색과 파란색 1 개가있다.

제 3의 빨간색은 음모 1과 음모 2의 합계이며, 나는 파란색으로 절반과 파란색으로 절반 음표를 갖고 싶습니다. -pylab

x=arange(0,4,0.1) 

exp1 = e**(-x/5) 
exp2 = e**(-x/1) 
exp3 = e**(-x/5) +e**(-x/1) 

figure() 
plot(x,exp1) 
plot(x,exp2) 
plot(x,exp1+exp2) 
title('Exponential Decay') 


annotate(r'$e^{-x/5}$', xy=(x[10], exp1[10]), xytext=(-20,-35), 
     textcoords='offset points', ha='center', va='bottom',color='blue', 
      bbox=dict(boxstyle='round,pad=0.2', fc='yellow', alpha=0.3), 
      arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0.95', 
          color='b')) 

annotate(r'$e^{-x/1}$', xy=(x[10], exp2[10]), xytext=(-5,20), 
     textcoords='offset points', ha='center', va='bottom',color='green', 
      bbox=dict(boxstyle='round,pad=0.2', fc='yellow', alpha=0.3), 
      arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=-0.5', 
          color='g')) 

annotate(r'$e^{-x/5} + e^{-x/1}$', xy=(x[10], exp2[10]+exp1[10]), xytext=(40,20), 
     textcoords='offset points', ha='center', va='bottom', 
      bbox=dict(boxstyle='round,pad=0.2', fc='yellow', alpha=0.3), 
      arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=-0.5', 
          color='red')) 

ipython

은 가능합니까?

+0

@bli [이 질문에 대한 답변] (https://stackoverflow.com/questions/9169052/partial-coloring-of-text-in-matplotlib)을 보았습니까? – ImportanceOfBeingErnest

+0

감사합니다. 이 대답은 실제로 적절합니다. https://stackoverflow.com/a/42768093/1878788 – bli

답변

7

하나의 주석에 여러 색상을 사용할 수 있다고 생각하지 않습니다. 알고있는 한, annotate은 하나의 텍스트 객체 만 매개 변수로 사용하며 텍스트 객체는 단일 색상 만 지원합니다. 따라서 필자가 아는 바로는이 기능을 자동으로 수행하는 "원시"또는 "우아한"방법이 없습니다.

그러나 해결 방법이 있습니다. 그래프에 임의의 텍스트 개체를 여러 개 배치 할 수 있습니다. 그래서 여기 내가 그것을 할 거라고 방법 : 내가 무슨 짓을

fig1 = figure() 
# all the same until the last "annotate": 
annotate(r'$e^{-x/5}$'+r'$e^{-x/1}$', xy=(x[10], exp2[10]+exp1[10]), xytext=(40,20), 
     textcoords='offset points', ha='center', va='bottom',color='white', 
      bbox=dict(boxstyle='round,pad=0.2', fc='yellow', alpha=0.3), 
      arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=-0.5', 
          color='r')) 

fig1.text(0.365, 0.62, r'$e^{-x/5}$', ha="center", va="bottom", size="medium",color="blue") 
fig1.text(0.412, 0.62, r'$e^{-x/1}$', ha="center", va="bottom", size="medium",color="green") 

했다 :

  1. 내가 주석 color='black'을 설정;
  2. 0.5와 0.5의 두 텍스트 객체를 만들었습니다 (중심은 fig1입니다).
  3. 에 의해 생성 된 검은 색 텍스트와 대략 겹칠 때까지 수동으로 위치를 변경했습니다 (두 번의 호출에서 두 번째로 볼 수있는 값인 text).
  4. color='white' 주석을 설정하므로 겹치는 텍스트의 색상을 방해하지 않습니다.

다음은 출력입니다 :

multi-colour annotated graph

그것은 매우 우아하지, 그리고 그것은 미세 조정할 위치를 일부 플로팅을 필요로하지 않습니다,하지만 작업이 이루어집니다. 여러 플롯을해야하는 경우

는, 아마도 배치를 자동화하는 방법이있다 : 당신이 fig1 객체를 저장하지 않는 경우, text의 좌표가 실제 X가, y는 좌표 그래프-I 찾아 조금 더 열심히 그 함께 작업하려면 어노테이션의 xy 좌표를 사용하여 자동으로 생성 할 수 있습니까? 나에게 문제가 될만한 소리는 아니지만, 그렇게한다면 코드를보고 싶다.

+2

이것을 플로팅 한 후에 나는 여러분의 플롯에'+'가 있음을 깨달았습니다. 나는 그 지시가 여분의'text'로 그것을 계획하는 데 충분하다는 것을 확신합니다. [이 답변] (http://stackoverflow.com/a/9185143/3540074)도 체크 아웃 할 수있는보다 우아한 방법을 제공하지만 작동시키지 못했습니다. – kadu

1

r'$\textcolor{blue}{e^{-x/5}} + \textcolor{green}{e^{-x/1}}$'을 사용하여 텍스트를 파란색으로 반쯤 녹색으로 만들 수 있습니다. 예를 들어 자신의 코드를 사용하여 :

enter image description here

이미지는 다음 코드에 의해 생성됩니다. matplotlib v2.1.2에서 기본값 matplotlibrc 설정으로 테스트하십시오.당신은 pgf 백엔드를 사용할 필요가

  1. :

    import matplotlib as matplotlib 
    matplotlib.use('pgf') 
    matplotlib.rc('pgf', texsystem='pdflatex') # from running latex -v 
    preamble = matplotlib.rcParams.setdefault('pgf.preamble', []) 
    preamble.append(r'\usepackage{color}') 
    
    from numpy import * 
    from matplotlib.pyplot import * 
    
    x=arange(0,4,0.1) 
    
    exp1 = e**(-x/5) 
    exp2 = e**(-x/1) 
    exp3 = e**(-x/5) +e**(-x/1) 
    
    figure() 
    plot(x,exp1) 
    plot(x,exp2) 
    plot(x,exp1+exp2) 
    title('Exponential Decay') 
    
    
    annotate(r'$e^{-x/5}$', xy=(x[10], exp1[10]), xytext=(-20,-25), 
         textcoords='offset points', ha='center', va='bottom',color='blue', 
         bbox=dict(boxstyle='round,pad=0.2', fc='yellow', alpha=0.3), 
         arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0.95', 
              color='b')) 
    
    annotate(r'$e^{-x/1}$', xy=(x[10], exp2[10]), xytext=(25,20), 
         textcoords='offset points', ha='center', va='bottom',color='green', 
         bbox=dict(boxstyle='round,pad=0.2', fc='yellow', alpha=0.3), 
         arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=-0.5', 
              color='g')) 
    
    annotate(r'$\textcolor{blue}{e^{-x/5}} + \textcolor[rgb]{0.0, 0.5, 0.0}{e^{-x/1}}$', 
         xy=(x[10], exp2[10]+exp1[10]), xytext=(40,20), 
         textcoords='offset points', ha='center', va='bottom', 
         bbox=dict(boxstyle='round,pad=0.2', fc='yellow', alpha=0.3), 
         arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=-0.5', 
              color='red')) 
    
    savefig('test.png') 
    

    은 다음과 같이 변경하여 코드는 주로. pgf.preamble

  2. 에서
  3. Usepackage color 그래서 xytext 변경, 제 1 및 제 2 주석과 약간의 중복이있다.
  4. 제 2 주석의 color='g'은 실제로 rgb의 (0, 255, 0)과 같이 순수한 "녹색"색상을 사용하지 않았습니다. \textcolor[rgb]{0.0, 0.5, 0.0}은 비슷하게 보입니다.
+0

감사합니다. 필자의 경우 필자는 TeX에 대한 메모리 문제가 있었는데, 아마도 산점도에 음모를 꾸미는 데 중요한 포인트가 있었기 때문일 것입니다. 나는 'texsystem'에''lualatex ''를 사용하여이 문제를 해결했다. – bli

+0

@bli, 예,'matplotlib.rc ('pgf', texsystem = 'pdflatex')의 줄은 지워 져야합니다. 기본 tex 시스템도 작동한다고 생각합니다. – gepcel

관련 문제