Cap. Rodgers
Cap. Rodgers

Reputation: 33

Legend problems with 2 y axis in python

I have created a 2 y axis plot with the left axis has a bar graph and the right axis has 2 line graphs. I am having difficulty getting the legend to have both the bar and line graphs on it. I can plot the legends separately but I would like to have them together. Here is the work I have done so far.

import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv('data.csv')
x = df["date"]
y1 = df["line 1"]
y2 = df["line 2"]
z = df["bar 1"]
y_pos = np.arange(len(x))

lns1 = plt.bar(y_pos,z)
plt.ylabel('bar 1')
plt.xlabel('date')
plt.legend([lns1], ["bar 1"])
plt.twinx()
lns2 = plt.plot(y_pos,y1,'r-',linewidth=2.5)
lns3 = plt.plot(y_pos,y2,color='orange',linewidth=2.5)
plt.ylabel('L-SLOC')
plt.xticks(y_pos, x)
plt.xlabel('date')
plt.title('Title of graph')

plt.legend(["line 1", "line 2"],loc="upper left")


plt.draw()
plt.show()`

Upvotes: 2

Views: 83

Answers (1)

Ilario Pierbattista
Ilario Pierbattista

Reputation: 3265

Instead of

plt.legend([lns1], ["bar 1"])

and

plt.legend(["line 1", "line 2"],loc="upper left")

You could try this:

plt.legend([lns1, lns2, lns3], ["bar 1", "line 1", "line 2"],loc="upper left")

Upvotes: 1

Related Questions