将图例放在子图的位置
Put legend on a place of a subplot
我想在中心子图的某个地方放置一个图例(并将其删除)。
我写了这段代码:
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()
我不知道如何隐藏中心情节。为什么传说没有出现?
这个link没有帮助http://matplotlib.org/1.3.0/examples/pylab_examples/legend_demo.html
您的代码有几个问题。在你的 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()
这给了我下面的图像:
我想在中心子图的某个地方放置一个图例(并将其删除)。 我写了这段代码:
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()
我不知道如何隐藏中心情节。为什么传说没有出现?
这个link没有帮助http://matplotlib.org/1.3.0/examples/pylab_examples/legend_demo.html
您的代码有几个问题。在你的 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()
这给了我下面的图像: