python - 对 groupby 进行子绘制,然后按 groupby 绘制

标签 python pandas matplotlib

您好,我正在尝试绘制分类数据,其描述:

data_df = pd.DataFrame({'Date': ['2018-09-14 00:00:22',
                                '2018-09-14 00:01:46',
                                '2018-09-14 00:01:56',
                                '2018-09-14 00:01:57',
                                '2018-09-14 00:01:58',
                                '2018-09-14 00:02:05'],
                        'userID': [33, 33, 33, 20, 20, 20],
                        'device': ['LIGHT', 'LIGHT', 'FAN', 'LIGHT', 'FAN', 'FAN'],
                        'description': ['ON', 'DIM', 'ON', 'ON', 'ON', 'OFF']})

data_df

我想要的是通过对 'device' 进行分组来绘制它们,但在此之前我想按行对 'userID' 进行子绘制,以便将它们分开按'userID',每条线图均根据'device'名称进行分组。

我还尝试了分组依据和绘图,但它说我的描述不是数字,因为它是分类的。日期是 x 轴,描述是 y 轴。

最佳答案

看起来您可能正在尝试绘制 userIDdevice 组随时间变化的描述。显然,description需要转换为数值变量,所以我冒昧地将ON编码为1,DIM编码为0.5,OFF编码为0。以下代码应该可以解决您的问题。

data_df['Date'] = pd.to_datetime(data_df['Date'])

def desc_num(x):
    if x == 'ON':
        return 1
    elif x == 'DIM':
        return 0.5
    else:
        return 0

data_df['desc_num'] = data_df['description'].apply(desc_num)    

## Creating groups of `userID` and `device`
groups = data_df.groupby(['userID', 'device'])

for g in groups:
    plt.plot(g[1]['Date'], g[1]['desc_num'])
    plt.xlabel('Time')
    plt.ylabel('description Status')
    plt.title('Time Series of userID: {0}, for device: {1}'.format(g[1]['userID'][0], g[1]['device'][0]))
    plt.show()
    plt.close()

输出(您应该看到每个子组的这样的图):

enter image description here

关于python - 对 groupby 进行子绘制,然后按 groupby 绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52378481/

相关文章:

python - Django - url 中的 View 或条件根据参数是否具有值或为 NONE 选择两种 url 模式之一

python - 在 Numpy/Pandas 中生成所有平行对角线总和的直接方法?

python - matplotlib从url : TypeError: a bytes-like object is required,而不是 'str'读取数据

Python:导入matplotlib但无法使用imshow

python - 错误的解释器没有这样的文件或目录/usr/bin/python

python - Popen/Wait - 等待永远不会结束

matplotlib - 在 3D Matplotlib 中只绘制一个点

python - 格式化日期时间变量将缺失的时间值作为 00 :00:00. 使用 Python

python - 使用 Pandas 移动分类值窗口