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

mzsu5hc0  于 2023-03-13  发布在  其他
关注(0)|答案(3)|浏览(148)

我想把图例设置为水平显示。我不是指Matplotlib legend vertical rotation文章中描述的图例的 text。我的 actual case包括了用小部件指定的任意数量的序列。但是下面的例子代表了挑战的要点:

代码段:

# 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()

情节:

默认布局似乎是垂直的。看看help(ax.legend)docs的细节,似乎没有一个直接的方法来将其更改为水平的。或者有吗?

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

yvgpqqbh

yvgpqqbh1#

在图例中指定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()
brccelvz

brccelvz2#

我相信你所说的水平,是指你希望图例中列出的点彼此相邻,而不是垂直。

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

ercv8c1e

ercv8c1e3#

您要指定ncol

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

相关问题