2017-01-10 72 views
0

我想在一个中央的副场地上放置一个传说(并将其删除)。 我写了这个代码:将传说放在一个地方的一个小区

import matplotlib.pylab as plt 
import numpy as np 

f, ax = plt.subplots(3,3) 
x = np.linspace(0, 2. * np.pi, 1000) 
y = np.sin(x) 

for axis in ax.ravel(): 
    axis.plot(x, y) 
    legend = axis.legend(loc='center') 

plt.show() 

我不知道如何隐藏一个中心情节。为什么传说没有出现?

example plot

这个环节并没有帮助http://matplotlib.org/1.3.0/examples/pylab_examples/legend_demo.html

回答

2

有几个问题与您的代码。在for循环中,您试图在每个轴上绘制一个图例(loc="center"指的是轴,而不是图),但是您尚未在图例中给出绘图标签。

您需要选择循环中的中心轴,并只显示该轴的图例。如果你不想在那里有线,这个循环的迭代应该没有plot调用。

import matplotlib.pylab as plt 
import numpy as np 

f, ax = plt.subplots(3,3) 
x = np.linspace(0, 2. * np.pi, 1000) 
y = np.sin(x) 

handles, labels = (0, 0) 

for i, axis in enumerate(ax.ravel()): 

    if i == 4: 
     axis.set_axis_off() 
     legend = axis.legend(handles, labels, loc='center') 
    else: 
     axis.plot(x, y, label="sin(x)") 

    if i == 3: 
     handles, labels = axis.get_legend_handles_labels() 

plt.show() 

这给了我下面的图片:

enter image description here

就像我在下面的代码已经做了你可以用一组条件句这样做