简体   繁体   English

在绘制两个Pandas系列后,在matplotlib中创建图例

[英]Creating legend in matplotlib after plotting two Pandas Series

I plotted two Pandas Series from the same DataFrame with the same x axis and everything worked out fine. 我用相同的x轴从相同的DataFrame绘制了两个Pandas系列,一切都很好。 However, when I tried to manually create a Legend, it appears but only with the title and not with the actually content. 但是,当我尝试手动创建一个图例时,它只显示标题而不是实际内容。 I've tried other solutions without any luck. 我试过没有运气的其他解决方案。 Here's my code: 这是我的代码:

    fig = plt.figure()
    ax1 = fig.add_subplot(111)
    ax2 = ax1.twinx()

    width = .3

    df.tally.plot(kind='bar', color='red', ax=ax1, width=width, position=1, grid=False)
    df.costs.plot(kind='bar', color='blue', ax=ax2, width=width, position=0, grid=True)

    ax1.set_ylabel('Tally')
    ax2.set_ylabel('Total Cost')

    handles1, labels1 = ax1.get_legend_handles_labels()
    handles2, labels2 = ax2.get_legend_handles_labels()

    plt.legend([handles1, handles2], [labels1, labels2], loc='upper left', title='Legend')
    plt.show()
    plt.clf()

Maybe you have a good reason to do it your way, but if not, this is much easier: 也许你有充分的理由按照你的方式去做,但如果没有,这就容易多了:

In [1]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Optional, just better looking
import seaborn as sns

# Generate random data
df = pd.DataFrame(np.random.randn(10,3), columns=['tally', 'costs', 'other'])
df[['tally', 'costs']].plot(kind='bar', width=.3)
plt.show();

Out[1]:

情节


Edit 编辑

After learning that this is because you have a much different scale for the other one, here's the pandas approach: 在得知这是因为你的另一个规模大不相同之后,这是大熊猫的方法:

# Generate same data as Jianxun Li
np.random.seed(0)
df = pd.DataFrame(np.random.randint(50,100,(20,3)), columns=['tally', 'costs', 'other'])
df.costs = df.costs * 5

width = .3

df.tally.plot(kind='bar', color='#55A868', position=1, width=width, legend=True, figsize=(12,6))
df.costs.plot(kind='bar', color='#4C72B0', position=0, width=width, legend=True, secondary_y=True)

plt.show();

在此输入图像描述

Something like this? 像这样的东西?

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# your data
# ===============================
np.random.seed(0)
df = pd.DataFrame(np.random.randint(50,100,(20,3)), columns=['col1', 'col2', 'col3'])
df.col2 = df.col2 * 5


# bar plot with twinx
# ===============================    
fig, ax = plt.subplots()
width=0.3

ax.bar(df.index, df.col1, width=width, color='red', label='col1_data')
ax.legend(loc='best')
ax2 = ax.twinx()
ax2.bar(df.index+width, df.col2, width=width, color='blue', label='col2_data')
ax2.legend(loc='best')

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM