简体   繁体   English

Lineplot - 为奇数子图绘制单个图例

[英]Lineplot - plot a single legend for uneven number of subplots

I'm working on the following graph where I'd like to plot is single legend that applies to all, essentially this would be a small box where blue color line is AB=0 and green line is AB = 1.我正在绘制下图,我想在其中绘制适用于所有人的单个图例,本质上这将是一个小框,其中蓝色线为 AB = 0,绿色线为 AB = 1。

Moreover, I'm using plt.subplot(... since it is possible that might have to deal with uneven number of columns to plot.此外,我正在使用plt.subplot(...因为它可能必须处理奇数列来绘制。

I tried positioning it outside of the box both it was not visible anywhere.我试着把它放在盒子外面,它在任何地方都看不到。

阴谋

plt.figure(figsize=(16,10))
plt.subplots_adjust(hspace=0.3)
plt.suptitle("Some title", fontsize=18, y=0.95)
plt.style.use('seaborn-darkgrid')
for i, col in enumerate(tms_0.columns):
    ax = plt.subplot(3,4,i+1)
    ax.plot(tms_0.index, tms_0[col], label=col, color='skyblue')
    ax.plot(tms_1.index, tms_1[col], label=col, color='green')
    #plt.legend(loc='upper left')
    #ax.set_title(col.upper())
    ax.set_xticks([])
fig.legend(["X", "Y"], loc='lower right', bbox_to_anchor=(1,-0.1), ncol=2, bbox_transform=fig.transFigure)
plt.show()

col in this code is actually a column in the dataframe so I can't use it in the normal fashion which is why I'm using it in the set_title .此代码中的col实际上是数据框中的一列,因此我不能以正常方式使用它,这就是我在set_title中使用它的原因。

I found some sort of option based on this thread How to manually create a legend我发现了一些基于这个线程的选项如何手动创建图例

legend_elements = [plt.Line2D([0], [0], color='skyblue', lw=2.5, label='ClientAB=0'),
                   plt.Line2D([0], [0], color='green', lw=2.5, label='ClientAB=1')]
ax.legend(handles=legend_elements, bbox_to_anchor=(1.2, 4.05))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM