2013-04-27 27 views
1

我在Python中的pyplot中创建了图。每个小区包含两个或更多个小区。我知道我可以通过定义参数loc静态地在图中放置一个图例;但是,我选择的位置有时会覆盖我的情节中的数据。我将如何动态地将图例放置在干扰数据的位置上?动态地将图例置于图中

+1

'loc = 0'('best')设置不起作用吗? – tacaswell 2013-04-27 19:12:08

回答

2

正如tcaswell已经说明,使用ax.legend(loc='best')

import matplotlib.pyplot as plt 
import numpy as np 
pi = np.pi 
sin = np.sin 
t = np.linspace(0.0, 2 * pi, 50) 
markers = ['+', '*', ',', ] + [r'$\lambda$'] 
phases = [0, 0.5] 
fig, ax = plt.subplots(len(phases)) 
for axnum, phase in enumerate(phases): 
    for i, marker in enumerate(markers, 1): 
     ax[axnum].plot(t, i*sin(2*t + phase*pi), marker=marker, 
        label='$i,\phi = {i},{p}$'.format(i=i, p=phase)) 
    ax[axnum].legend(loc='best', numpoints=1) 
plt.show() 

enter image description here

有趣的是,图例的位置不固定。如果您使用GUI移动图形,图例的位置将自动重新调整。