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

时间:2015-07-21 18:27:09

标签: python pandas matplotlib plot

我使用相同的x轴从相同的DataFrame绘制了两个Pandas系列,一切都很好。但是,当我尝试手动创建一个图例时,它只显示标题而不是实际内容。我没有运气就尝试了其他解决方案。这是我的代码:

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

2 个答案:

答案 0 :(得分:2)

也许你有充分的理由按照你的方式去做,但如果没有,这就容易多了:

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]:

Plot

修改

在得知这是因为你的另一个人的规模大不相同之后,这是大熊猫的方法:

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

enter image description here

答案 1 :(得分:1)

这样的东西?

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

enter image description here