你还没有指定你想要什么样的酒吧类型,但我猜go.Bar() 会做。但我们可以改变这一点。对于分组和聚合,我将使用以下方法:
df['date'] = pd.to_datetime(df["date"])
df['months'] = df['date'].dt.month_name()
df_months = df.groupby(['months']).agg('mean').reset_index()
new_order = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
df_months['months'] = pd.Categorical(df_months['months'], categories=new_order, ordered=True)
df_months = df_months.sort_values('months')
为什么这么复杂?因为我假设您希望在 x 轴上有月份名称。在按月份名称对值进行分组和聚合之后,月份的顺序可能会变得混乱。上面有些费力的方法确保不会发生这种情况,并且您可以按照正确的月份顺序绘制此条形图:
完整代码:
import pandas as pd
import plotly.graph_objects as go
df = pd.DataFrame({'id': {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F'},
'date': {0: '2020-01-01',
1: '2020-01-11',
2: '2020-01-21',
3: '2020-01-21',
4: '2020-02-01',
5: '2020-02-01'},
'grade': {0: 100, 1: 200, 2: 500, 3: 300, 4: 100, 5: 200}})
df['date'] = pd.to_datetime(df["date"])
df['months'] = df['date'].dt.month_name()
df_months = df.groupby(['months']).agg('mean').reset_index()
new_order = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
df_months['months'] = pd.Categorical(df_months['months'], categories=new_order, ordered=True)
df_months = df_months.sort_values('months')
fig=go.Figure(go.Bar(x=df_months.months, y=df_months.grade))
fig.show()