Iterating through a dataframe and plotting counts of each column

Question:

I am analyzing some survey data that contains a column for each day of the week. There can only be two values in the columns, 1 if the respondents do work on that day, and a 0 if they do not. I would like to be able to have a count plot for each day of the week. However, when I run the code below, the first seven subplots are blank and the eighth subplot shows a count plot. The title of that last plot if Monday while the x-axis is labeled as Sunday.

f, ax = plt.subplots(nrows = 4, ncols = 2, figsize=(12,18))
work_days = df[['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']]
row = 0
col = 0
for i in work_days:
    g = sns.countplot(x=i,data=work_days)
    g.set(title = column)
    col += 1
    if col == 2:
        col = 0
        row += 1

plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=.5)

I’ve also tried the code below:

f, ax = plt.subplots(nrows = 4, ncols = 2, figsize=(12,18))
work_days = df[['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']]
row = 0
col = 0
for i, col in enumerate(work_days):
    g = sns.countplot(x=i,data=work_days)
    g.set(title = column)
    col += 1
    if col == 2:
        col = 0
        row += 1

plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=.5)

This code produces a TypeError: ‘int’ object is not iterable.

Any help on this would be appreciated.

Asked By: gernworm

||

Answers:

If I understand correctly:

df = pd.DataFrame(data = np.random.randint(low=0,high=2,size=(10,5)),
                  columns=['Mon','Tues','Weds','Thurs','Fri'])
df2 = df.melt(var_name='day', value_name='worked')
g = sns.FacetGrid(data=df2, col='day', col_wrap=3)
g.map(sns.countplot, 'worked', order=[0,1])
plt.show()

enter image description here

Answered By: Brendan
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.