4

I plotted two Pandas Series from the same DataFrame with the same x axis and everything worked out fine. 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()
2
  • try passing label='label' kwarg? Commented Jul 21, 2015 at 18:59
  • Why do you need to do it this way? Why not df[['tally', 'costs']].plot(... ? Commented Jul 21, 2015 at 19:36

2 Answers 2

3

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

Plot


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

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

This does work, but I need two separate y axis because the data values are so different for tally and costs. Thanks for the input!
1

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

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.