2016-07-30 45 views
4

我想做一個註釋,類似於here,但我需要顯示範圍,而不是單個點的x。這就像技術圖紙中的dimension lines如何在matplotlib中註釋x軸的範圍?


這裏是我所期待的一個例子:

import matplotlib.pyplot as plt 
import numpy as np 

xx = np.linspace(0,10) 
yy = np.sin(xx) 

fig, ax = plt.subplots(1,1, figsize=(12,5)) 
ax.plot(xx,yy) 
ax.set_ylim([-2,2]) 
# ----------------------------------------- 
# The following block attempts to show what I am looking for 
ax.plot([4,6],[1,1],'-k') 
ax.plot([4,4],[0.9,1.1],'-k') 
ax.plot([6,6],[0.9,1.1],'-k') 
ax.annotate('important\npart', xy=(4, 1.5), xytext=(4.5, 1.2)) 

enter image description here


如何標註一個範圍在maplotlib圖?


我使用:

蟒蛇:3.4.3 + numpy的:1.11.0 + matplotlib:1.5.1

回答

2

你可以使用兩次調用ax.annotate - 一個以添加文本一到畫一個箭頭與平端跨越範圍要註釋:

import matplotlib.pyplot as plt 
import numpy as np 

xx = np.linspace(0,10) 
yy = np.sin(xx) 

fig, ax = plt.subplots(1,1, figsize=(12,5)) 
ax.plot(xx,yy) 
ax.set_ylim([-2,2]) 

ax.annotate('', xy=(4, 1), xytext=(6, 1), xycoords='data', textcoords='data', 
      arrowprops={'arrowstyle': '|-|'}) 
ax.annotate('important\npart', xy=(5, 1.5), ha='center', va='center') 

enter image description here

1

使用ali_m's answer,我可以定義這個功能,也許這可以成爲別人的某個時候:)


功能

def annotation_line(ax, xmin, xmax, y, text, ytext=0, linecolor='black', linewidth=1, fontsize=12): 

    ax.annotate('', xy=(xmin, y), xytext=(xmax, y), xycoords='data', textcoords='data', 
      arrowprops={'arrowstyle': '|-|', 'color':linecolor, 'linewidth':linewidth}) 
    ax.annotate('', xy=(xmin, y), xytext=(xmax, y), xycoords='data', textcoords='data', 
      arrowprops={'arrowstyle': '<->', 'color':linecolor, 'linewidth':linewidth}) 

    xcenter = xmin + (xmax-xmin)/2 
    if ytext==0: 
     ytext = y + (ax.get_ylim()[1] - ax.get_ylim()[0])/20 

    ax.annotate(text, xy=(xcenter,ytext), ha='center', va='center', fontsize=fontsize) 

呼叫

annotation_line(ax=ax, text='Important\npart', xmin=4, xmax=6, \ 
        y=1, ytext=1.4, linewidth=2, linecolor='red', fontsize=18) 
有用

輸出

enter image description here