【问题标题】:Creating legend in matplotlib after plotting two Pandas Series绘制两个 Pandas 系列后在 matplotlib 中创建图例
【发布时间】:2015-07-22 05:49:13
【问题描述】:

我用相同的 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()

【问题讨论】:

  • 尝试传递label='label'kwarg?
  • 为什么需要这样做?为什么不df[['tally', 'costs']].plot(...

标签: python pandas matplotlib plot


【解决方案1】:

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

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


编辑

在得知这是因为您对另一个的规模有很大不同之后,这里是 pandas 方法:

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

【讨论】:

  • 这确实有效,但我需要两个单独的 y 轴,因为数据值对于计数和成本是如此不同。感谢您的意见!
【解决方案2】:

这样的?

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

【讨论】:

    猜你喜欢
    • 2019-08-22
    • 1970-01-01
    • 2018-02-24
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    • 1970-01-01
    • 2015-01-09
    相关资源
    最近更新 更多