Issue
Consider the following example
import pandas as pd
import matplotlib.pyplot as plt
ddd = pd.DataFrame({'time': [1,2,3,4],
'var1': [1,4,6,3],
'var2': [4,3,2,1]})
fig, ax = plt.subplots()
for col in ['var1', 'var2']:
ddd.set_index('time')[col].plot(label = col)
which gives:
However, as you can see, the legend are not correctly labeled even though I used the label
argument in the plot()
call. Do you know how to fix that while keeping the loop structure (adding charts sequentially while sharing the ax
)?
Thanks!
Solution
in the code, your are on the right path, but there is a little problem. you set the index inside the loop, and that is what causes the labeling issue as dataframe ddd's index is changed on each iteration. you can set it before you run the for loop so it is outside the loop like this to make the legend show correctly and also let both columns share the same axis:
fig, ax = plt.subplots()
ddd.set_index('time', inplace=True)
for col in ['var1', 'var2']:
ddd[col].plot(label=col, ax=ax) # use the ax parameter to share the same axis
ax.legend()
plt.show()
Answered By - jeffreyohene
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.