Reputation: 1051
I have a dataframe named "original_filtered_df". I am trying to plot, for each possible pair of values from two columns ("COLOR", "SIZE"), two other columns ("WEIGHT", "HEIGHT") over time ("DATE").
The below code plots correctly. It creates multiple plots, each for one possible value of ("COLOR", "SIZE"). Each plot contains two lines, one for "WEIGHT" and one for "HEIGHT". However, the legend names do not say "WEIGHT" or "HEIGHT". They both say "DATE" (the x-axis). How can I force the legend to refer to the y-axis data, so that the names will say "WEIGHT" and "HEIGHT"?
import matplotlib.pyplot as plt
for combo in original_filtered_df.groupby(['COLOR', 'SIZE'], as_index=True):
color = combo[0][0]
size = combo[0][1]
filtered_df = original_filtered_df[(original_filtered_df["COLOR"] == color) & (original_filtered_df["SIZE"] == size)]
plt.figure()
filtered_df.plot(x="DATE", y="WEIGHT", color=(1,0,0))
filtered_df.plot(x="DATE", y="HEIGHT", color=(0,1,0))
#patches, labels = ax.get_legend_handles_labels()
#ax.legend(patches, labels, loc='center left', bbox_to_anchor=(1, 0.5))
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.title("COLOR " + str(color) + ", SIZE " + size)
Upvotes: 2
Views: 797
Reputation: 1051
I'm not sure why the label for the legend was defaulting to the x-axis, but I solved this by doing the following when plotting:
filtered_df.plot(x="DATE", y="WEIGHT", color=(1,0,0), label="WEIGHT")
filtered_df.plot(x="DATE", y="HEIGHT", color=(0,1,0), label="HEIGHT")
With this, the legend function used the correct y-axis labels.
Upvotes: 1