我想指定图例是垂直显示还是水平显示。我的意思不是说Matplotlib图例垂直旋转中描述的图例文本。我的实际案例包括使用小部件指定的任意数量的系列。但是以下示例代表了挑战的要点:
片段:
# 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()
Run Code Online (Sandbox Code Playgroud)
情节:
默认布局似乎是垂直的。查看help(ax.legend)和文档的细节,似乎没有一种直接的方法可以将其更改为水平。还是在那里?
编辑-所需的图例:(使用MS Paint)
mau*_*uve 18
我相信水平,你的意思是你希望图例列出彼此相邻的点而不是垂直。
plt.legend(loc="lower left", mode = "expand", ncol = 3) #expand stretches it along the bottom
# while ncol specifies the number of columns
Run Code Online (Sandbox Code Playgroud)
https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend
小智 8
由于声誉较低,我无法将此作为评论添加到已接受的答案中,但对于像我这样不断复制粘贴情节代码但希望“ncol”值自动化的人来说,这是一个小小的改进:
plt.legend(loc="lower left", ncol = len(ax.lines) )
ncol在图例中指定参数。在您的情况下,例如:
plt.legend(loc="lower left", ncol=len(df.columns))
Run Code Online (Sandbox Code Playgroud)
这是我在脚本中更改的唯一一行。
工作完整代码:
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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
917 次 |
| 最近记录: |