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

Matplotlib: how to show legend elements horizontally?

我想指定图例是垂直显示还是水平显示。 我的意思不是说Matplotlib图例垂直旋转中描述的图例文本。 我的实际案例包括使用小部件指定的任意数量的系列。 但是以下示例代表了挑战的要点:

片段:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 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 = plt.subplot()
for col in (df.columns):
    plt.plot(df[col])
plt.legend(loc="lower left")
plt.xticks(rotation=90)
plt.show()

情节:

enter image description here

默认布局似乎是垂直的。
查看help(ax.legend)和docs的详细信息,似乎没有简单的方法可以将其更改为水平。 还是在那里?

编辑-所需的图例:(使用MS Paint)

enter image description here


在图例中指定ncol参数。 在您的情况下,例如:

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

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

工作完整代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
2
plt.legend(loc="lower left", mode ="expand", ncol = 3) #expand stretches it along the bottom
# while ncol specifies the number of columns

https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend