我试着把多个条形图垂直地画在一起。应该有一个标记的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()

这有以下问题:
由于某些原因,生成的第一个图是空白的。
我希望同一个图上的子图垂直分开,而不是很多分开的图
我的dataframe有39行,但是上面的方法根本没有绘制最后4个点。
完整的输入数据是:
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()

python - 如何让 Pandas 在相同的图上以相同的y轴范围绘制-LMLPHP

09-27 20:28