Ger*_*nuk 107 matplotlib legend title subplot
我开始使用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
Run Code Online (Sandbox Code Playgroud)
(对此有何看法?:))每个子图都有相同的样式功能.
现在我正试图获得所有子图的全局标题,以及解释所有样式的全球传奇.此外,我需要使字体很小,以适应那里的所有200种样式(我不需要完全独特的样式,但至少有一些尝试)
有人可以帮我解决这个任务吗?
orb*_*kst 171
全局标题:在较新版本的matplotlib中,可以使用Figure.suptitle().
from pylab import *
fig = gcf()
fig.suptitle("Title centered above all subplots", fontsize=14)
Run Code Online (Sandbox Code Playgroud)
Ado*_*obe 50
除了orbeckst答案之外,人们可能还想将子图移位.这是一个OOP风格的MWE:
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")
Run Code Online (Sandbox Code Playgroud)
得到:
对于图例标签,可以使用下面的内容.Legendlabels是保存的情节线.modFreq是与绘图线对应的实际标签的名称.然后第三个参数是图例的位置.最后,你可以传递任何参数,因为我在这里,但主要需要前三个.此外,如果在plot命令中正确设置标签,则应该这样做.要使用location参数调用图例,它会在每个行中找到标签.我有更好的运气制作我自己的传奇如下.似乎在所有情况下都无法正常工作的情况下工作.如果你不明白让我知道:
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)
Run Code Online (Sandbox Code Playgroud)
您还可以使用腿来更改图例或几乎任何图例的参数.
上述评论中所述的全局标题可以通过根据提供的链接添加文本来完成: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')
Run Code Online (Sandbox Code Playgroud)