2015-07-21 4 views
2

Я построил две серии Pandas из того же DataFrame с той же осью x, и все получилось отлично. Однако, когда я пытался создать легенду вручную, она появляется только с заголовком, а не с фактическим содержимым. Я пробовал другие решения без везения. Вот мой код:Создание легенды в matplotlib после построения двух серий 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() 
+0

попробуйте передать 'метку = 'label'' kwarg? – tacaswell

+0

Зачем вам это нужно? Почему не 'df [['tally', 'costs']]. Plot (...'? –

ответ

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

+0

Это действительно работает, но мне нужна две отдельные оси y потому что значения данных настолько различны для подсчета и затрат. Спасибо за ввод! – Fonti

+0

Я отредактировал свой ответ, зная это –

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

+0

Не мое идеальное решение, но хорошая работа. Спасибо! – Fonti

Смежные вопросы