Creating a plot with multiple columns

How can multiple columns be plotted, where the column headers are on the x-axis?

Data frame:

In[] nfl.head()
Out[]: 
   NfL_BL  NfL_V02    NfL_V04    NfL_V06  NfL_V08    NfL_V12
0     5.67      NaN   6.150000   7.940000     9.03  40.200001
5     7.88     6.66   7.100000   8.190000     8.39   8.570000
11   15.50      NaN  17.799999  19.799999    24.50  23.900000
16    6.52     6.38   7.220000   8.980000     8.00   7.350000
22    4.53      NaN   4.960000   5.900000     4.98   4.930000
...

It is a temporal (from BL to V12), and I wanted the columns to be the x-axis.

I got some awful plots and hists in any of my attempts.

Upvotes: 0

Views: 120

Answers (1)

Trenton McKinney
Trenton McKinney

Reputation: 62533

import pandas as pd
import numpy as np

# test data and dataframe
data = {0: {'NfL_BL': 5.67, 'NfL_V02': np.nan, 'NfL_V04': 6.15, 'NfL_V06': 7.94, 'NfL_V08': 9.03, 'NfL_V12': 40.200001},
        5: {'NfL_BL': 7.88, 'NfL_V02': 6.66, 'NfL_V04': 7.1, 'NfL_V06': 8.19, 'NfL_V08': 8.39, 'NfL_V12': 8.57},
        11: {'NfL_BL': 15.5, 'NfL_V02': np.nan, 'NfL_V04': 17.799999, 'NfL_V06': 19.799999, 'NfL_V08': 24.5, 'NfL_V12': 23.9},
        16: {'NfL_BL': 6.52, 'NfL_V02': 6.38, 'NfL_V04': 7.22, 'NfL_V06': 8.98, 'NfL_V08': 8.0, 'NfL_V12': 7.35},
        22: {'NfL_BL': 4.53, 'NfL_V02': np.nan, 'NfL_V04': 4.96, 'NfL_V06': 5.9, 'NfL_V08': 4.98, 'NfL_V12': 4.93}}

nfl = pd.DataFrame.from_dict(data, orient='index')

# display(nfl)
    NfL_BL  NfL_V02  NfL_V04  NfL_V06  NfL_V08  NfL_V12
0     5.67      NaN     6.15     7.94     9.03    40.20
5     7.88     6.66     7.10     8.19     8.39     8.57
11   15.50      NaN    17.80    19.80    24.50    23.90
16    6.52     6.38     7.22     8.98     8.00     7.35
22    4.53      NaN     4.96     5.90     4.98     4.93

# plot dataframe
nfl.plot()

enter image description here

# bar plot
nfl.plot.bar()

enter image description here

  • .transpose and plot
  • This will set the column headers as the index, and make it possible to plot them on the x-axis.
# transposed dataframe nfl.T

            0     5     11    16    22
NfL_BL    5.67  7.88  15.5  6.52  4.53
NfL_V02    NaN  6.66   NaN  6.38   NaN
NfL_V04   6.15  7.10  17.8  7.22  4.96
NfL_V06   7.94  8.19  19.8  8.98  5.90
NfL_V08   9.03  8.39  24.5  8.00  4.98
NfL_V12  40.20  8.57  23.9  7.35  4.93

# plot a transposed dataframe
nfl.T.plot.bar()

enter image description here

For a histogram of all the values

  • I recommend using seaborn, which is a high-level API for matplotlib.
    • It makes working with different shapes of data, easier.
  • seaborn.distplot
import seaborn as sns

# plot
p = sns.distplot(a=nfl, kde=False)
p.set_xlabel('bins')
p.set_ylabel('counts')

enter image description here

Upvotes: 2

Related Questions