python - 绘制包含 HH :MM format in a single figure matplotlib 的数据帧

标签 python pandas dataframe matplotlib

我的问题(写在下面的末尾)与在不同子图中绘制两个 DataFrame 的直方图有关(下面的情况 1)与在同一图中绘制它们(下面的情况 2)。以 1 小时的间隔作为分组标准绘制直方图。两个 DataFrame 都有一个单独的列,其中包含 "HH:MM" 格式的时间。

# Defining the two DataFrames
df_in = pd.DataFrame({'time': ['12:20', '12:06', '11:30', '11:03', '10:44', '10:50', '11:52', 
                               '12:21', '9:58', '12:43','12:56', '13:27', '12:14',]})

df_out = pd.DataFrame({'time': ['19:40', '19:44', '19:21', '20:37', '20:27', '18:46', '19:42', 
                                '18:12', '19:08', '21:09', '18:37', '20:34', '20:15']})

情况 1:在不同的子图中绘制两个 DataFrame

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import FixedFormatter

fig, axes = plt.subplots(1, 2, figsize=(9, 3))

colors = ['r', 'b']
titles = ['df-in', 'df-out']

# Looping over the dataframes and plotting them in subfigures
for df, ax, c, t in zip([df_in, df_out], axes.flatten(), colors, titles):
    df['hour'] = pd.to_datetime(df['time'], format='%H:%M')
    df.set_index('hour', drop=False, inplace=True)
    df = df['hour'].groupby(pd.Grouper(freq='60Min')).count()
    df.plot(kind='bar', color=c, ax=ax)
    ticklabels = df.index.strftime('%H:%Mh')
    ax.xaxis.set_major_formatter(FixedFormatter(ticklabels))
    ax.set_title(t, fontsize=18)
plt.show()

情况 1 的输出

enter image description here


情况 2:在同一张图中绘制两个 DataFrame

fig, axes = plt.subplots(figsize=(7, 3))

# Looping over the dataframes and plotting them in subfigures
for df, c, t in zip([df_in, df_out], colors, titles):
    df['hour'] = pd.to_datetime(df['time'], format='%H:%M')
    df.set_index('hour', drop=False, inplace=True)
    df = df['hour'].groupby(pd.Grouper(freq='60Min')).count()
    df.plot(kind='bar', color=c, ax=axes)
    ticklabels = df.index.strftime('%H:%Mh')
    axes.xaxis.set_major_formatter(FixedFormatter(ticklabels))
plt.show() 

情况 2 的输出

enter image description here

在这两种情况下,字符串格式化代码都取自this。问题。如您所见,分别绘制时,红色和蓝色直方图在 12:00 和 19:00 分别具有最大值。但是当我在同一个图中绘制它们时,两个直方图重叠并且最大值不在 12:00 和 19:00 h。这个问题似乎微不足道,但我不确定出了什么问题。


我的问题是:在情况 2 中需要修改什么才能使直方图很好地分离和区分(而不是重叠),因为它们清楚地以 12 为中心:00 和 19:00?欢迎任何指点和建议。

最佳答案

还可以使用sns强大的hue:

# convert to time
df_in.time = pd.to_datetime(df_in.time)
df_out.time = pd.to_datetime(df_out.time)

# mark the series/dataframe and join
df_in['df'] = 'df_in'
df_out['df'] = 'df_out'
df = pd.concat((df_in,df_out))

# groupby hours:
df = df.groupby(['df',df.time.dt.hour]).size().reset_index()

# plot with sns
plt.figure(figsize=(10,6))
sns.barplot(x='time', 
            y=0,
            hue='df', 
            dodge=False,
            data=df)
plt.show()

输出:

enter image description here


编辑:要绘制 x 轴从 7 到 23 的条形图,我们可以在绘制之前reindex:

df = (df.groupby(['df', df.time.dt.hour]).size()
        .reset_index(level=0).reindex(range(7,24))
        .reset_index()
     )

sns 条形图给出:

enter image description here

关于python - 绘制包含 HH :MM format in a single figure matplotlib 的数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56247991/

相关文章:

python - 如何用最后一个非空白单元格填充数据框中的空白单元格?

python - 类型错误 : __str__ returned non-string (type PhoneNumber)

python - 将样式应用于保存到 HTML 文件的 Pandas 数据框

Python Pandas : create rank columns, 移动原始列最大排名

python - Dataframe 简单移动平均线 (SMA) 计算

python - 根据值 Pandas Dataframe 获取所有其他列

python - 哪个 Python 模块可以在 while 循环中监控 3 个按键组合?

python - 我的代码在哪里被破坏[Python初学者]

python - 为 panda 切片添加值的有效方法

python - DataFrame 在列表中重复字典