Create histogram for grouped column

Question:

How can I create a plot with one row and three columns where in each column I plot a histogram? The data comes from this DataFrame:

import pandas as pd
import matplotlib as plt
d = {'col1': ['A','A','A','A','A','A','B','B','B','B','B','B','C','C','C','C','C','C'], 
     'col2': [3, 4, 3, 4, 6, 7, 8, 9, 3, 2, 3, 4, 5, 3, 4, 1, 2, 6 ]}
df = pd.DataFrame(data=d)

In the DataFrame we have three groups (A,B,C) but I could have N groups and I still want to have one graph with one row and each column is a histogram for each group.

Asked By: Bruno Guarita

||

Answers:

I think this is the code you searching for:

import pandas as pd
import matplotlib.pyplot as plt
d = {'col1': ['A','A','A','A','A','A','B','B','B','B','B','B','C','C','C','C','C','C'], 
     'col2': [3, 4, 3, 4, 6, 7, 8, 9, 3, 2, 3, 4, 5, 3, 4, 1, 2, 6 ]}
df = pd.DataFrame(data=d)

keys = sorted(df['col1'].unique())

vals = []
for k in keys:
    vals.append(sum(df.loc[df['col1'] == k]['col2']))

print(vals)

plt.bar(keys, vals)
plt.show()

This is what you get in this example:
enter image description here

Ask me if you need an explanation (or just google it☻).

Answered By: ykaner

You can pivot your data frame and chain the plot command to produce the figure.

import pandas as pd
import matplotlib.pyplot as plt

d = {'Category': ['A','A','A','A','A','A','B','B','B','B','B','B','C','C','C','C','C','C'], 
     'Values': [3, 4, 3, 4, 6, 7, 8, 9, 3, 2, 3, 4, 5, 3, 4, 1, 2, 2 ]}
df = pd.DataFrame(d)

df.pivot(columns='Category', values='Values').plot(kind='hist', subplots=True, rwidth=0.9, align='mid')

enter image description here

Edit: You can use the code below to plot all subplots in one row. However, for more than three categories the plots start looking very squashed.

df2 = df.pivot(columns='Category', values='Values')
color = ['blue', 'green', 'red']
idx = np.arange(1, 4)
plt.subplots(1, 3)
for i, col, colour in zip(idx, df2.columns, color):
    plt.subplot(1, 3, i)
    df2.loc[:, col].plot.hist(label=col, color=colour, range=(df['Values'].min(), df['Values'].max()), bins=11)
    plt.yticks(np.arange(3))
    plt.legend()

enter image description here

Answered By: KRKirov

You can create a row of subplots and fill each with a histogram:

import pandas as pd
from matplotlib import pyplot as plt
from matplotlib.ticker import FormatStrFormatter

#define toy dataset
d = {'col1': ['A','A','A','A','A','A','B','B','B','B','B','B','C','C','C','C','C','C'], 
     'col2': [3, 4, 3, 4, 6, 7, 8, 9, 3, 2, 3, 4, 5, 3, 4, 1, 2, 6 ]}
df = pd.DataFrame(data=d)

#number of bins for histogram
binnr = 4
#group data in dataframe
g = df.groupby("col1")
#create subplots according to unique elements in col1, same x and y scale for better comparison
fig, axes = plt.subplots(1, len(g), sharex = True, sharey = True)
#just in case you will extend it to a 2D array later
axes = axes.flatten()

#minimum and maximum value of bins to have comparable axes for all histograms
binmin = df["col2"].min()
binmax = df["col2"].max()

#fill each subplot with histogram
for i, (cat, group) in enumerate(g): 
    axes[i].set_title("graph {} showing {}".format(i, cat))
    _counts, binlimits, _patches = axes[i].hist(group["col2"], bins = binnr, range = (binmin, binmax))

#move ticks to label the bin borders
axes[0].set_xticks(binlimits)
#prevent excessively long tick labels
axes[0].xaxis.set_major_formatter(FormatStrFormatter('%0.1f'))
plt.tight_layout()
plt.show()

Sample output:
enter image description here

Answered By: Mr. T