1

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?

Adriaan
  • 17,741
  • 7
  • 42
  • 75
  • 1
    ax2 doesn't know anything about ax1. This is one of the pitfalls of `twinx()`. You're probably best off just setting the legend of ax2 manually (e.g. `ax2.legend(['cm','l/s'])`). – cosmic_inquiry Jan 23 '19 at 17:47

1 Answers1

1

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?

Moritz
  • 105
  • 2
  • 6
  • 1
    Hey Moritz, Thank you very much, i choose the first solution and it works ! My question about the spaces is about stackoverflow, to get the codelabel you have to insert a space on every line of code. I tried the Tab to move the hole block but it wont work, maybe i have to use clips. Best regards Kai – Kai_hismelf Jan 25 '19 at 11:23