Matplotlib:如何水平显示图例元素?

57

我想将图例设置为水平显示。我不是指类似于Matplotlib legend vertical rotation中描述的图例的文本。我的实际情况包括使用小部件指定的任意数量的系列。但是以下示例代表了这个挑战的要点:

代码片段:

# Imports
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# data
np.random.seed(123)
x = pd.Series(np.random.randn(100),index=pd.date_range('1/1/2000', periods=100)).cumsum()
y = pd.Series(np.random.randn(100),index=pd.date_range('1/1/2000', periods=100)).cumsum()
z = pd.Series(np.random.randn(100),index=pd.date_range('1/1/2000', periods=100)).cumsum()
df = pd.concat([x,y,z], axis = 1)

# plot 
ax = df.plot()
plt.legend(loc="lower left")
plt.show()

情节:

enter image description here

默认布局似乎是垂直的。 查看help(ax.legend)docs的详细信息,似乎没有直接改变为水平的简单方法。或者有吗?


编辑 - 期望的图例:(使用 MS Paint)

enter image description here


1
这是一个很好的链接,可以帮助你解决问题。https://dev59.com/eFcP5IYBdhLWcg3w_e12 - Krish
此问题已在 如何将图例放在绘图外部 的多个答案中得到解决。 - Trenton McKinney
@TrentonMcKinney 你好,Trenton!虽然在你提到的答案中可能会找到解决此问题的方法,但这两个问题非常不同,旨在解决两个完全不同的问题。这是标题和问题本身的情况。此外,在帖子中使用ncols是一个完整的解决方案,而在链接的帖子中只是部分解决方案。在那里使用ncols甚至不是必需的解决方案的一部分。因此,我认为这个问题根本不是重复的。或者我漏掉了什么吗? - vestland
1
@TrentonMcKinney 谢谢您分享您的知识!我已经更新了代码片段,以便更好地匹配较新版本的Matplotlib功能。 - vestland
3个回答

73

在图例中指定ncol参数。 在您的情况下,可以这样写:

在图例中指定ncol参数。 在您的情况下,可以这样写:

plt.legend(loc="lower left", ncol=len(df.columns))

这是我在您的脚本中唯一更改的一行。

完整可工作的代码:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# data
np.random.seed(123)
x = pd.Series(np.random.randn(100),index=pd.date_range('1/1/2000', periods=100)).cumsum()
y = pd.Series(np.random.randn(100),index=pd.date_range('1/1/2000', periods=100)).cumsum()
z = pd.Series(np.random.randn(100),index=pd.date_range('1/1/2000', periods=100)).cumsum()
df = pd.concat([x,y,z], axis = 1)

# plot
ax = plt.subplot()
for col in (df.columns):
    plt.plot(df[col])
plt.legend(loc="lower left", ncol=len(df.columns))
plt.xticks(rotation=90)
plt.show()

1
谢谢您的回答!现在我知道要搜索什么了(ncol而不是方向,垂直,水平或其他),我必须说这非常容易。对于那些感兴趣的人,matplotlib文档中有一个很好的示例在这里 - vestland

22

12

您想指定 ncol

plt.legend(loc="lower left", ncol = len(ax.lines) )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接