0

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.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
gernworm
  • 322
  • 3
  • 16

1 Answers1

1

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

Brendan
  • 3,901
  • 15
  • 23
  • Yes! This is exactly what I was looking for. Thanks Brendan! – gernworm Jul 15 '19 at 17:05
  • @miguelf88 Please consider accepting / upvoting the answer if it was helpful. Also, if you haven't already, take a look at the documentation for [`seaborn.FacetGrid`](https://seaborn.pydata.org/generated/seaborn.FacetGrid.html) - it explains the various options you can pass, which are quite helpful in refining the overall look of the graph. – Brendan Jul 15 '19 at 17:10
  • Could you explain why the first two plots are not labeled along the x-axis? – gernworm Jul 15 '19 at 17:10
  • @miguelf88 That's how FacetGrid works by default -- overlapping axes are labeled at the bottom to avoid duplicating information which is the same. If you wish to override this, see [this answer](https://stackoverflow.com/questions/52182322/repeating-x-axis-labels-for-all-facets-using-facetgrid-in-seaborn). – Brendan Jul 15 '19 at 17:17
  • Thanks Brendan. You've been a huge help. – gernworm Jul 15 '19 at 17:19