3
$\begingroup$

I want to plot a bar of my data grouped per week. I made the following dataframe, with nonsense data, but it should do the trick.

What I want to do is plot per week a bar chart (%)

Does anyone know how I can do this? I'm using datetime64 so can this be done easily?

I want to make one graph which contains 52x3 bars.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import random

date_expected = np.arange('2005-06', '2006-07', dtype= 'datetime64[D]')
cat = ['True','False', 'Maybe']

value = [random.choice(cat) for i in range(len(date_expected))]

data = {'Date_expected': date_expected,  'Value': value }
df = pd.DataFrame(data)
df = pd.DataFrame(data)


print(df.head())
$\endgroup$
  • $\begingroup$ To clarify - you want a bar chart with the counts of values for each week? That is, each week is its own bar chart? $\endgroup$ – Wes Feb 12 '19 at 14:02
  • $\begingroup$ No, sorry, I think i did not clarify that part well enough. I want one graph. with 52 times 4 bars. tnx $\endgroup$ – jenny Feb 12 '19 at 14:05
1
$\begingroup$

Is this what you want to do? I am not sure why you need 52 x 4 columns, since you have 3 categories in your Value field.

What I did is to create a new column with the number of Week in that Year, using the dt.week.

import pandas as pd
import numpy as np
import random

date_expected = np.arange('2006-01', '2006-06', dtype= 'datetime64[D]')
cat = ['True','False', 'Maybe']

value = [random.choice(cat) for i in range(len(date_expected))]

data = {'Date_expected': date_expected,  'Value': value }
df = pd.DataFrame(data)
df = pd.DataFrame(data)


df['week'] = df['Date_expected'].dt.week

df.groupby('Value').week.value_counts().unstack(0).plot.bar(figsize=(10,30))
|improve this answer|||||
$\endgroup$
  • $\begingroup$ Thank you that was what i wanted exactly, the 4 columns was a mistake, i ment 3 $\endgroup$ – jenny Feb 12 '19 at 14:31
  • $\begingroup$ Great then. Happy to helped. If you are satisfied you can mark as best and/or upvote the answer to let other users know that this is what you needed $\endgroup$ – Tasos Feb 12 '19 at 14:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.