TAGS :Viewed: 13 - Published at: a few seconds ago

[ Change plot label when plotting different dataframes in pandas ]

I aggregated on pivot tables some time series information, so each pivot table have columns labeled 2015, 2014, etc. I want to compare each pivot table, so I'm plotting them on the same axis:

print pv_test_A.columns
Int64Index([2010, 2011, 2012, 2013, 2014, 2015], dtype='int64')

print pv_test_B.columns
Int64Index([2010, 2011, 2012, 2013, 2014, 2015], dtype='int64')

fig, axes = plt.subplots()

in this case, each line will have the same label on the graph, 2015. I tried passing the label argument to the plot to no effect. Is there a way to rename the labels without having to resort to using plt.legend or annotate?

Answer 1

You could use .rename():

pv_test_A.loc[:,[2015]].rename(columns={2015: "New Label A"}).plot(ax=axes)
pv_test_B.loc[:,[2015]].rename(columns={2015: "New Label B"}).plot(ax=axes)

The underlying data is preserved, but the columns to be plotted are given a different label for plotting purposes.