【问题标题】:Put legend on a place of a subplot将图例放在子图的位置
【发布时间】:2017-05-24 12:11:40
【问题描述】:
我想在中心子图的某个位置放置一个图例(并删除它)。
我写了这段代码:
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()
我不知道如何隐藏中心情节。为什么没有出现图例?
此链接没有帮助http://matplotlib.org/1.3.0/examples/pylab_examples/legend_demo.html
【问题讨论】:
标签:
python
matplotlib
legend
subplot
【解决方案1】:
您的代码存在几个问题。在您的 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()
这给了我以下图像: