Kai_hismelf
Kai_hismelf

Reputation: 41

Only one dataname shows in the legend

I like to display a diagram of two data columns. The problem about it is that the legend shows only the last name l/s.

Here is my diagram:

Diagram

import pandas as pd
import matplotlib.pyplot as plt

Tab = pd.read_csv('Mst01.csv', delimiter=';')

x =  Tab['Nr. ']
y1 = Tab['cm']
y2 = Tab['l/s']

fig, ax1 = plt.subplots()

 ax2 = ax1.twinx()
 ax1.plot(x, y1, 'g-', label='cm')
 ax2.plot(x, y2, 'b-', label='l/s')

 ax1.set_xlabel('Nr.')
ax1.set_ylabel('cm', color='g')

ax2.set_ylabel('l/s', color='b')


plt.title('Mst01')

 plt.legend()

 plt.show()

If I do ax1.legend() ax2.legend()

both legends will displayed but one above the other.

By the way, is there a easyier way the get the spaces for every line of code?

Upvotes: 1

Views: 529

Answers (1)

Moritz
Moritz

Reputation: 165

Good evening!

so you got two possibilities either you add the plots together or you use fig.legend()

here is some sample code which yields to the solution

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# Create Example Dataframe
dummy_data = np.random.random_sample((100,2))
df = pd.DataFrame(dummy_data, columns=['Col_1', 'Col_2'])
df.Col_2 = df.Col_2*100

# Create Figure
fig, ax = plt.subplots()

col_1 = ax.plot(df.Col_1, label='Col_1', color='green')
ax_2 = ax.twinx()
col_2 = ax_2.plot(df.Col_2, label='Col_2', color='r')

# first solution
lns = col_1+col_2
labs = [l.get_label() for l in lns]
ax.legend(lns, labs, loc='upper right')

# secound solution
fig.legend()
fig

The solution can be derived from this question.

What do you mean by spaces? you mean the indention of e.g. a for loop?

Upvotes: 1

Related Questions