149

我从 matplot 开始并管理了一些基本的情节,但现在我发现很难发现如何做一些我现在需要的东西 :(

我的实际问题是如何在带有子图的图形上放置全局标题和全局图例。

我正在做 2x3 子图,其中有很多不同颜色的图表(大约 200 个)。为了区分(大多数)我写了类似的东西

def style(i, total):
    return dict(color=jet(i/total),
                linestyle=["-", "--", "-.", ":"][i%4],
                marker=["+", "*", "1", "2", "3", "4", "s"][i%7])

fig=plt.figure()
p0=fig.add_subplot(321)
for i, y in enumerate(data):
    p0.plot(x, trans0(y), "-", label=i, **style(i, total))
# and more subplots with other transN functions

(对此有什么想法吗?:))每个子图都具有相同的样式功能。

现在我正在尝试获得所有子图的全局标题以及解释所有样式的全局图例。另外我需要使字体很小以适应那里的所有 200 种样式(我不需要完全独特的样式,但至少需要一些尝试)

有人可以帮我解决这个任务吗?

4

4 回答 4

243

全局标题:在较新版本的 matplotlib 中,可以使用Figure.suptitle()方法Figure

import matplotlib.pyplot as plt
fig = plt.gcf()
fig.suptitle("Title centered above all subplots", fontsize=14)

或者(基于@Steven C. Howell下面的评论(谢谢!)),使用matplotlib.pyplot.suptitle()函数:

 import matplotlib.pyplot as plt
 # plot stuff
 # ...
 plt.suptitle("Title centered above all subplots", fontsize=14)
于 2012-02-10T00:47:24.373 回答
87

In addition to the orbeckst answer one might also want to shift the subplots down. Here's an MWE in OOP style:

import matplotlib.pyplot as plt

fig = plt.figure()
st = fig.suptitle("suptitle", fontsize="x-large")

ax1 = fig.add_subplot(311)
ax1.plot([1,2,3])
ax1.set_title("ax1")

ax2 = fig.add_subplot(312)
ax2.plot([1,2,3])
ax2.set_title("ax2")

ax3 = fig.add_subplot(313)
ax3.plot([1,2,3])
ax3.set_title("ax3")

fig.tight_layout()

# shift subplots down:
st.set_y(0.95)
fig.subplots_adjust(top=0.85)

fig.savefig("test.png")

gives:

enter image description here

于 2015-08-21T10:25:38.237 回答
7

对于图例标签,可以使用如下所示的内容。图例标签是保存的情节线。modFreq 是对应于绘图线的实际标签的名称。那么第三个参数就是图例的位置。最后,您可以像我在这里一样传递任何参数,但主要需要前三个。此外,如果您在绘图命令中正确设置标签,您应该这样做。只需使用 location 参数调用 legend 并在每一行中找到标签。我有更好的运气创造我自己的传奇如下。似乎在所有情况下都可以正常工作。如果您不明白,请告诉我:

legendLabels = []
for i in range(modSize):
    legendLabels.append(ax.plot(x,hstack((array([0]),actSum[j,semi,i,semi])), color=plotColor[i%8], dashes=dashes[i%4])[0]) #linestyle=dashs[i%4]       
legArgs = dict(title='AM Templates (Hz)',bbox_to_anchor=[.4,1.05],borderpad=0.1,labelspacing=0,handlelength=1.8,handletextpad=0.05,frameon=False,ncol=4, columnspacing=0.02) #ncol,numpoints,columnspacing,title,bbox_transform,prop
leg = ax.legend(tuple(legendLabels),tuple(modFreq),'upper center',**legArgs)
leg.get_title().set_fontsize(tick_size)

您还可以使用腿来更改字体大小或图例的几乎任何参数。

上述评论中所述的全局标题可以通过根据提供的链接添加文本来完成:http: //matplotlib.sourceforge.net/examples/pylab_examples/newscalarformatter_demo.html

f.text(0.5,0.975,'The new formatter, default settings',horizontalalignment='center',
       verticalalignment='top')
于 2011-09-23T12:26:56.583 回答
4

suptitle似乎要走的路,但对于它的价值,它figure有一个transFigure你可以使用的属性:

fig=figure(1)
text(0.5, 0.95, 'test', transform=fig.transFigure, horizontalalignment='center')
于 2012-10-14T23:53:08.457 回答