【问题标题】:How to add days of the week x axis labels [duplicate]如何添加星期几x轴标签[重复]
【发布时间】:2018-05-06 18:35:56
【问题描述】:

我有一个数据框,其中每一行都与一周中的某一天相关,从星期日开始。总共有 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()

这给出了:

如何按星期几标记 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

【问题讨论】:

  • 你是第一个在这里询问如何在 matplotlib 图上绘制一周中的几天的人吗?其他答案在多大程度上没有帮助?
  • 如果您的数据没有日期列,如何按天绘制?
  • @cᴏʟᴅsᴘᴇᴇᴅ 实际上他只是提到了星期几(所以我们可以取任何日期并从星期日开始):)。或者只是分配周日-周六。
  • @cᴏʟᴅsᴘᴇᴇᴅ 第一行是周日,然后是周一,以此类推。
  • 我认为这被错误地标记为重复,因为您要求其他内容。希望我的回答能帮到你! :)

标签: python pandas matplotlib


【解决方案1】:

这样的?

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 张图片,这是一张:

【讨论】:

  • 为什么会遭到反对?
  • @eleanora 我不知道。没关系,对你有帮助吗?
  • 谢谢。我认为你需要for i in range(int(round(len(df)/7))):,因为round 返回一个浮点数。
  • 它似乎没有绘制最后几天,因为它似乎只涵盖了整整几周。另外,如何使每个图形的 y 轴范围相同?我尝试在循环中添加plt.ylim([0,10]),但效果不佳。
  • @eleanora 我们可以为此使用子图。使用 matplotlib,您总是需要大量格式化:/
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-27
  • 2012-04-26
  • 2017-05-16
  • 1970-01-01
  • 2015-08-08
相关资源
最近更新 更多