简体   繁体   English

matplotlib 并排放置图例

[英]matplotlib put legend side-by-side

I am doing a series of plots inside a for loop:我正在 for 循环中绘制一系列图:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,1, 100)
y = np.sin(x)

for i in range(1,6):
    plt.plot(x, i*y, label=f't= {i}')
    
    plt.plot(x[::2], i*y[::2], marker='o', linestyle='None', markersize=2,label=f'a= {i}')
    
plt.legend(loc='best', ncol=2)

The output is: output 是:

在此处输入图像描述

I would like the legend to be:我希望传说是:

在此处输入图像描述

How can I access the legend and make it like in the image above?如何访问图例并使其如上图所示?

If you don't give extra arguments to legend , it will put the artists in the legend in the order they were created and also sort them by container (but here you don't care since you only have artists belonging to ax.lines ).如果您不向legend提供额外的 arguments ,它将按照创建顺序将艺术家放入图例中,并按容器对它们进行排序(但在这里您不在乎,因为您只有属于ax.lines的艺术家) . You should sort the handles manually to get the result you desire then give it to legend .您应该手动对句柄进行排序以获得所需的结果,然后将其提供给legend

Here it's pretty simple:这很简单:

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
x = np.linspace(0,1, 100)
y = np.sin(x)

for i in range(1,6):
    ax.plot(x, i*y, label=f't= {i}')    
    ax.plot(x[::2], i*y[::2], marker='o', linestyle='None', markersize=2,label=f'a= {i}')

handles = [line for x in ("t", "a") for line in ax.lines  if line.get_label().startswith(x)]
# handles = [line for m in ("None", "o") for line in ax.lines if line.get_marker() == m]      
ax.legend(handles=handles, loc='best', ncol=2)

Notice that we have several solutions to order the artists.请注意,我们有几个解决方案来订购艺术家。 Here we can follow the pattern in the line labels, or simply their marker type.在这里,我们可以遵循线标签中的模式,或者只是它们的标记类型。

在此处输入图像描述

This seems like a clean and object-orientated solution to me.对我来说,这似乎是一个干净且面向对象的解决方案。 For a solution which modifies your code much less, you could do:对于修改代码少得多的解决方案,您可以这样做:

for i in range(1,6):
    plt.plot(x, i*y, label=f't= {i}')
for i in range(1,6):    
    plt.plot(x[::2], i*y[::2], marker='o', linestyle='None', markersize=2,label=f'a= {i}')

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

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