我试图在两个地块下绘制一个图例(使用twinx创建)。我希望图例在底部中心绘制,与4列对齐。到目前为止没有成功。如何针对整个绘图制作图例,而不仅仅是单个轴对象。有什么帮助吗?
import matplotlib.pyplot as plt;
import numpy as np;
from matplotlib import rc;
filename = 'ml.pdf';
fig, ax1 = plt.subplots(frameon=False);
rc('mathtext', default='regular');
rc('lines',lw=2.6);
rc('lines',mew=2.4);
rc('text', usetex=True);
x = np.array([5,10,20,50]);
dp_g = np.array([23.43, 29.93, 36.50, 46.07]);
mr_g = np.array([25.33, 31.83, 38.39, 47.75]);
md_g = np.array([24.94, 31.33, 37.80, 47.10]);
sb_g = np.array([27.01, 34.86, 43.18, 54.35]);
lns1 = ax1.plot(x,dp_g,'bs:', label="MD\n($\lambda$=.8)");
lns2 = ax1.plot(x,mr_g,'bs--',label="MR\n($\lambda$=.1)");
lns3 = ax1.plot(x,md_g,'bs-.',label='MD');
lns4 = ax1.plot(x,sb_g,'bs-',label="SB\n($\gamma$=.1)");
ax1.set_ylabel('CG ($\times$ 100)',color='b',size=14);
ax1.set_ylim([20,57]);
ax1.set_xlim([4,51]);
ax1.set_xticks(x);
ax1.tick_params(axis='y', which=u'both', length=0, labelsize=14, colors='b');
ax1.tick_params(axis='x', which=u'both', length=0, labelsize=14);
ax2 = ax1.twinx();
dp_d = np.array([18.84, 19.55, 20.09, 20.08]);
mr_d = np.array([19.42, 19.73, 20.06, 20.04]);
md_d = np.array([19.02, 19.75, 20.28, 20.29]);
sb_d = np.array([20.81, 19.77, 19.20, 19.03]);
lns6 = ax2.plot(x,dp_d,'rv:',label="MD\n($\lambda$=.8)");
lns7 = ax2.plot(x,mr_d,'rv--',label="MR\n($\lambda$=.1)");
lns8 = ax2.plot(x,md_d,'rv-.',label='MD');
lns9 = ax2.plot(x,sb_d,'rv-',label="SB\n($\gamma$=.1)");
lns = lns1 + lns2 + lns3 + lns4 + lns6 + lns7 + lns8 + lns9;
labs = [l.get_label() for l in lns];
ax2.set_ylabel('LD ($\times$ 100)',color='r',size=14);
ax2.set_ylim([15,23]);
ax2.set_xlim([4,51]);
ax2.set_xticks(x);
ax2.tick_params(axis='y', which=u'both', length=0, labelsize=14, colors='r');
ax2.tick_params(axis='x', which=u'both', length=0, labelsize=14);
ax1.set_xlabel('\# of items',size=14);
borderaxespad=2.5, ncol = 1, fontsize='11.5');
lgd = ax1.legend(lns, labs, bbox_to_anchor=(1.01,1.0), loc='lower center', borderaxespad=2.5, ncol = 4, fontsize='14');
fig.savefig(filename,format='pdf',transparent=True, bbox_extra_artists=(lgd,), bbox_inches='tight');
答案 0 :(得分:0)
除了断行borderaxespad=2.5, ncol = 1, fontsize='11.5');
之外,我相信您要做的只是从图例定义中删除bbox_to_anchor=(1.01, 1.0)
。这样做会将图例放在图的底部中心(但图例非常宽,因此它将跨越图的整个宽度)。