如何添加星期几x轴标签

时间:2017-11-22 22:04:34

标签: python pandas matplotlib

我有一个数据框,其中每行与星期日的星期几相关。共有39行。我想一次一周地绘制Physical列中的数值,并在x轴上标记星期几。到目前为止我有这个:

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()

这给出了:

enter image description here

如何按星期几标记x轴,从星期日开始,将星期分开,以便它们垂直分开。

完整数据是:

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

1 个答案:

答案 0 :(得分:0)

这样的东西?

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()

返回6张图片,这是一张:

enter image description here