【问题标题】:Matplotlib: how to show legend elements horizontally?Matplotlib:如何水平显示图例元素?
【发布时间】:2019-02-25 16:23:48
【问题描述】:

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

片段:

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

剧情:

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


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

【问题讨论】:

标签: python matplotlib


【解决方案1】:

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

【讨论】:

  • 感谢您的回答!既然我知道要搜索什么(ncol 而不是方向、垂直、水平或其他),我不得不说这一切都非常容易。 matplotlib 文档有一个很好的例子here 供感兴趣的人使用。
【解决方案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

【讨论】:

    【解决方案3】:

    你想指定ncol

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

    【讨论】:

      猜你喜欢
      • 2020-12-09
      • 1970-01-01
      • 2014-01-29
      • 2011-05-31
      • 1970-01-01
      • 1970-01-01
      • 2015-03-06
      • 2010-09-20
      • 1970-01-01
      相关资源
      最近更新 更多