gpt4 book ai didi

python - 如何按两个变量分组的条形图

转载 作者:行者123 更新时间:2023-12-02 16:08:15 27 4
gpt4 key购买 nike

我有一个数量的 15 分钟时间步数据,多年来......

<表类="s-表"><头>日期时间数量<正文>2018-01-07 00:156.962018-01-07 00:306.482018-01-07 00:456.962018-01-07 01:006.72....

我正在使用 Pandas。如何生成横轴为月份的条形图;和每年的一系列(一组条形图);每个条形的高度是该月和该年的总量。

就像这样:

example plot

最佳答案

创建假数据框:

df = pd.DataFrame()
df['Datetime'] = pd.date_range(start = '01/07/2018', end = '13/08/2021', freq = '15min')
df['Quantity'] = np.random.rand(len(df))

从这一点开始,您应该提取月份和年份并将它们保存在单独的列中:

df['month'] = df['Datetime'].dt.month
df['year'] = df['Datetime'].dt.year

然后你必须计算每年的 'Quantity' 的总和:

df = df.groupby(by = ['month', 'year'])['Quantity'].sum().reset_index()

在这段话之后,你应该有一个像这样的数据框:

             Datetime  Quantity  month  year
0 2018-01-07 00:00:00 0.226113 1 2018
1 2018-01-07 00:15:00 0.222872 1 2018
2 2018-01-07 00:30:00 0.835484 1 2018
3 2018-01-07 00:45:00 0.775771 1 2018
4 2018-01-07 01:00:00 0.972559 1 2018
5 2018-01-07 01:15:00 0.418036 1 2018
6 2018-01-07 01:30:00 0.902843 1 2018
7 2018-01-07 01:45:00 0.012441 1 2018
8 2018-01-07 02:00:00 0.883437 1 2018
9 2018-01-07 02:15:00 0.183561 1 2018

现在可以绘制数据框了;使用 seaborn:

fig, ax = plt.subplots()

sns.barplot(ax = ax, data = df, x = 'month', y = 'Quantity', hue = 'year')

plt.show()

完整代码

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns


df = pd.DataFrame()
df['Datetime'] = pd.date_range(start = '01/07/2018', end = '13/08/2021', freq = '15min')
df['Quantity'] = np.random.rand(len(df))
df['month'] = df['Datetime'].dt.month
df['year'] = df['Datetime'].dt.year

df = df.groupby(by = ['month', 'year'])['Quantity'].sum().reset_index()


fig, ax = plt.subplots()

sns.barplot(ax = ax, data = df, x = 'month', y = 'Quantity', hue = 'year')

plt.show()

enter image description here

关于python - 如何按两个变量分组的条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68767771/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com