我正在尝试在彼此上方垂直绘制多个条形图。应该有一个标记的x轴(带有星期几)。到目前为止,我的代码是:
import pandas as pd
import matplotlib.pyplot as plt
import calendar
df = pd.read_csv("health.csv", header = None, names = ['Physical', 'Emotional'])
# 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(int(round(len(df)/7))):
plt.ylim([0,10])
df.iloc[i*7:(i+1)*7].set_index('DayOfTheWeek').plot(kind='bar')
plt.show()
这有以下问题:
完整的输入数据为:
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
为此,您可以先设置图形布局,然后将显式轴对象传递给pandas plot方法。然后,我有条件地仅在最后一个图上显示x轴标签。我还删除了到日期名称的映射-现在可以直接通过绘图完成。显然,如果出于其他原因需要,可以放回去!
import pandas as pd
import matplotlib.pyplot as plt
import calendar
df = pd.read_csv("health.csv", header = None, names = ['Physical', 'Emotional'])
# Get Dayofweek index number (start with 6 for sunday) 6,0,1....
df['DayOfTheWeek'] = [(i+6) % 7 for i in range(len(df))]
df_calendar = calendar.Calendar(firstweekday=6)
weeks = int(round(len(df)/7))
fig, axes = plt.subplots(weeks, 1, figsize=(6, weeks*3))
# Loop through the df (splitting week by week)
for i in range(weeks):
ax=axes[i]
df.iloc[i*7:(i+1)*7].set_index('DayOfTheWeek').plot(kind='bar', ax=axes[i])
ax.set_ylim([0,10])
ax.set_xlim([-0.5,6.5])
ax.set_xticks(range(7))
if i == 0:
ax.legend().set_visible(True)
else:
ax.legend().set_visible(False)
if i == weeks-1:
ax.set_xticklabels([calendar.day_name[weekday] for weekday in df_calendar.iterweekdays()])
ax.set_xlabel("Day of the week")
else:
ax.set_xticklabels([])
ax.set_xlabel("")
plt.savefig("health.png")
plt.show()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句