Matplotlib:如何水平显示图例元素? [英] Matplotlib: how to show legend elements horizontally?

查看:26
本文介绍了Matplotlib:如何水平显示图例元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想指定图例是垂直显示还是水平显示.我的意思不是像

默认布局似乎是垂直的.查看 help(ax.legend)

解决方案

在图例中指定 ncol 参数.在你的情况下是这样的:

plt.legend(loc="左下", ncol=len(df.columns))

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

完整的代码:

将pandas导入为pd导入matplotlib.pyplot作为plt将numpy导入为np# 数据np.random.seed(123)x = pd.Series(np.random.randn(100),index = pd.date_range('1/1/2000',period = 100)).cumsum()y = pd.Series(np.random.randn(100),index = pd.date_range('1/1/2000',period = 100)).cumsum()z = pd.Series(np.random.randn(100),index = pd.date_range('1/1/2000',period = 100)).cumsum()df = pd.concat([x,y,z],轴= 1)# 阴谋斧= plt.subplot()对于(df.columns)中的col:plt.plot(df[col])plt.legend(loc =左下",ncol = len(df.columns))plt.xticks(旋转=90)plt.show()

I'd like to specify whether or not the legend to be displayed vertically or horisontally. I do not mean the text of the legend like described in the post Matplotlib legend vertical rotation. My actual case includes an arbitrary number of series specified with a widget. But the following example represents the gist of the challenge:

Snippet:

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

Plot:

The default layout seems to be vertical. Looking at the details of help(ax.legend) and the docs , there does not seem to be a straight forward way to change this to horizontal. Or is there?


Edit - Desired Legend: (using MS Paint)

解决方案

Specify the ncol parameter in legend. In your case something like:

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

This is the only line I changed in your script.

Working full code:

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

这篇关于Matplotlib:如何水平显示图例元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆