-2

I have a dataframe in which each row relates to a day of the week, starting on Sunday. there are 39 rows in total. I would like to plot the numerical values from the column Physical one week at a time with the days of the week labelled on the x-axis. I have this so far:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("health.csv", header = None, names = ['Physical', 'Emotional'])
ax = df['Physical'].plot()
plt.show()

This gives:

enter image description here

How can I label the x-axis by the days of the week, starting on Sunday and split the weeks so that they are separated vertically.

The full data is:

5,5
6,7
6,9
6,7
5,6
7,9
5,9
6,7
7,6
7,4
7,5
6,7
7,9
7,9
5,6
8,7
9,9
7,7
7,6
7,8
7,9
7,9
7,6
7,8
6,6
6,6
6,7
6,6
6,5
6,6
7,5
7,5
7,5
7,6
7,5
8,6
7,6
7,7
6,6
Simd
  • 19,447
  • 42
  • 136
  • 271

1 Answers1

0

Something like this?

import pandas as pd
import calendar

df = pd.DataFrame({'Physical': {0: 5,
  1: 6,2: 6,3: 6,4: 5,5: 7,6: 5,7: 6,8: 7,9: 7,10: 7,11: 6,12: 7,
  13: 7,14: 5,15: 8,16: 9,17: 7,18: 7,19: 7,20: 7,21: 7,22: 7,23: 7,24: 6,25: 6,
  26: 6,27: 6,28: 6,29: 6,30: 7,31: 7,32: 7,33: 7,34: 7,35: 8,36: 7,37: 7,38: 6}})

# Get Dayofweek index number (start with 6 for sunday) 6,0,1....
df['DayOfTheWeek'] = [(i+6) % 7  for i in range(len(df))]

# Get a map to translate to day of week
d = dict(zip(range(7),list(calendar.day_name)))
df['DayOfTheWeek'] = df['DayOfTheWeek'].map(d)

# Loop through the df (splitting week by week)
for i in range(round(len(df)/7)):
    df.iloc[i*7:(i+1)*7].set_index('DayOfTheWeek').plot(kind='bar')

plt.show()

Returns 6 images, this is one:

enter image description here

Anton vBR
  • 18,287
  • 5
  • 40
  • 46
  • Why did this get a downvote? – Simd Nov 22 '17 at 22:44
  • @eleanora I don't know. Doesn't matter, does it help you? – Anton vBR Nov 22 '17 at 22:44
  • Thank you. I think you need `for i in range(int(round(len(df)/7))):` as round returns a float. – Simd Nov 23 '17 at 09:44
  • It doesn't plot the last few days it seems as it only seems to cover full weeks. Also, how do you get the y axis range to be the same for each graph? I tried adding `plt.ylim([0,10])` in the loop but that didn't work well. – Simd Nov 23 '17 at 10:04
  • @eleanora we could use subplots for that. With matplotlib you always need to format a lot :/ – Anton vBR Nov 23 '17 at 10:44
  • I could ask a separate question so I can accept two of your answers maybe :) – Simd Nov 23 '17 at 10:46
  • @eleanora No not necessary, but yeah that could be another question. But I think the answer is already out there on how to use subplots etc. – Anton vBR Nov 23 '17 at 13:01
  • https://stackoverflow.com/questions/47454335/how-to-get-pandas-to-plot-on-the-same-graph-with-the-same-y-axis-range Any help very much appreciated. – Simd Nov 23 '17 at 13:14