Row based chart plot (Seaborn or Matplotlib)

2019-08-10 17:58发布

问题:

Given that my data is a pandas dataframe and looks like this:

            Ref   +1    +2    +3    +4    +5    +6    +7  
 2013-05-28  1  -0.44  0.03  0.06 -0.31  0.13  0.56  0.81 
 2013-07-05  2   0.84  1.03  0.96  0.90  1.09  0.59  1.15 
 2013-08-21  3   0.09  0.25  0.06  0.09 -0.09 -0.16  0.56 
 2014-10-15  4   0.35  1.16  1.91  3.44  2.75  1.97  2.16 
 2015-02-09  5   0.09 -0.10 -0.38 -0.69 -0.25 -0.85 -0.47 

How can I plot a chart of the 5 lines (1 for each ref), where the X axis are the columns (+1, +2...), and starts from 0? If is in seaborn, even better. But matplotlib solutions are also welcome.

回答1:

Plotting a dataframe in pandas is generally all about reshaping the table so that the individual lines you want are in separate columns, and the x-values are in the index. Some of these reshape operations are a bit ugly, but you can do:

df = pd.read_clipboard()
plot_table = pd.melt(df.reset_index(), id_vars=['index', 'Ref'])
plot_table = plot_table.pivot(index='variable', columns='Ref', values='value')
# Add extra row to have all lines start from 0:
plot_table.loc['+0', :] = 0
plot_table = plot_table.sort_index()
plot_table
Ref          1     2     3     4     5
variable                              
+0        0.00  0.00  0.00  0.00  0.00
+1       -0.44  0.84  0.09  0.35  0.09
+2        0.03  1.03  0.25  1.16 -0.10
+3        0.06  0.96  0.06  1.91 -0.38
+4       -0.31  0.90  0.09  3.44 -0.69
+5        0.13  1.09 -0.09  2.75 -0.25
+6        0.56  0.59 -0.16  1.97 -0.85
+7        0.81  1.15  0.56  2.16 -0.47

Now that you have a table with the right shape, plotting is pretty automatic:

plot_table.plot()