gpt4 book ai didi

python - 如何更改时间序列的条形大小

转载 作者:太空宇宙 更新时间:2023-11-03 15:13:41 25 4
gpt4 key购买 nike

我正在努力对一段时间内英雄联盟玩家的游戏进行一些分析。我正在尝试使用plotly 创建直方图,日期范围在x 轴上,而没有。 y 上的游戏数量。这可行,但我无法获得每天的单独条形图,只能获得一个月的条形图。我尝试过使用 xaxis,'size' 对象,但这不会改变任何东西,我猜是因为 x 轴是日期形式。

那么问题来了,在 Plotly 中如何将直方图上的条形大小从每月 bin 大小更改为每日 bin 大小?

下面是代码示例:

from datetime import date, timedelta
import random
import plotly.plotly as py
import plotly.graph_objs as go
import numpy as np
from plotly import tools
from plotly.offline import *#plotly.offline.iplot()
init_notebook_mode(connected=True)
############## create date ranges #################

d1 = date(2014, 3, 22) # start date
d2 = date(2014, 6, 22) # end date

delta = d2 - d1 # timedelta
dates = []
for i in range(delta.days + 1):
dates.append((d1 + timedelta(days=i)))


#################################################


def games_p_day():
sizeo = 1
trace_total = go.Histogram(
y=[random.randint(1, 10) for y in range(1, 100)],
x=dates,
name = 'total games',
xbins=dict(
size=sizeo
)
)
trace_wins = go.Histogram(
y=[random.randint(1, 10) for y in range(1, 100)],
x=dates,
name = 'won games',
xbins=dict(
size=sizeo
)
)
trace_losses = go.Histogram(
y=[random.randint(1, 10) for y in range(1, 100)],
x=dates,
name = 'lost games',
xbins=dict(
size=sizeo
)
)
layout = dict(
title = "Wins and losses over time",
xaxis=dict(
rangeselector=dict(
buttons=list([
dict(count=1,
label='1m',
step='month',
stepmode='backward'),
dict(count=6,
label='6m',
step='month',
stepmode='backward'),
dict(step='all')
])
),
rangeslider=dict(),
type='date',

),
bargap=0.2,
bargroupgap=0.1)
data=[trace_total]
fig = go.Figure(data=data, layout=layout)
iplot(fig, filename = "Wins and losses over time")

games_p_day()

非常感谢任何帮助。哦,如果您看到任何其他可以帮助我的内容(即错误的代码结构),请告诉我!

最佳答案

直方图是 representation of the distribution的数值数据。在我看来,您的目标是对每日数据到每周数据进行聚合。也就是说,只要您希望在 x 轴上具有时间维度而不是计数、平均值或任何其他聚合函数。如果是这种情况,那么您面临的挑战的关键不在于绘图本身,而在于聚合和时间函数,例如 resample('W-Mon', on='index').sum()。以下是一些示例:

采样原始数据图:

enter image description here

原始数据代码:

import pandas as pd
import numpy as np
import datetime

# data
np.random.seed(12)
numdays=100
dates = pd.date_range('1/1/2020', periods=numdays)
games = np.random.randint(low=100, high=200, size=numdays).tolist()
losses = np.random.randint(low=0, high=100, size=numdays).tolist()
wins = list(np.array(games)-np.array(wins))
df = pd.DataFrame({'games': games,
'wins':wins,
'losses':losses}, index=dates)

# resample daily data to weekly sums
df2=df.reset_index().resample('W-Mon', on='index').sum()
df2['formatted_date'] = pd.to_datetime(df3.index)
df2['year'] = df2.formatted_date.apply(lambda x: x.year)
df2['week_of_year'] = df2.formatted_date.apply(lambda x: x.weekofyear)
df2['year_week'] = df2['year'].map(str)+'_'+df3['week_of_year'].map(str)

# build and show plotly plot for daily games
fig = go.Figure(data=[go.Bar(name='games', x=df.index, y=df['games'])])
fig.show()

每周汇总数据图。日期作为索引:

enter image description here

每周汇总数据的代码。日期作为索引:

# build and show plotly plot for weekly games. Dates as index
fig = go.Figure(data=[go.Bar(name='games', x=df2.index, y=df2['games'])])
fig.show()

每周汇总数据图。作为索引的年份和周数:

enter image description here

每周汇总数据的代码。作为索引的年份和周数:

# build and show plotly plot for weekly games. Year and week number as index
fig = go.Figure(data=[go.Bar(name='games', x=df2['year_week'], y=df2['games'])])
fig.show()

每周汇总数据图,按胜负划分:

enter image description here

每周汇总数据的代码,按胜负划分:

import pandas as pd
import numpy as np
import datetime

# data
np.random.seed(12)
numdays=100
dates = pd.date_range('1/1/2020', periods=numdays)
games = np.random.randint(low=100, high=200, size=numdays).tolist()
losses = np.random.randint(low=0, high=100, size=numdays).tolist()
wins = list(np.array(games)-np.array(wins))
df = pd.DataFrame({'games': games,
'wins':wins,
'losses':losses}, index=dates)

# resample daily data to weekly sums
df2=df.reset_index().resample('W-Mon', on='index').sum()
df2['formatted_date'] = pd.to_datetime(df3.index)
df2['year'] = df2.formatted_date.apply(lambda x: x.year)
df2['week_of_year'] = df2.formatted_date.apply(lambda x: x.weekofyear)
df2['year_week'] = df2['year'].map(str)+'_'+df3['week_of_year'].map(str)

fig = go.Figure(data=[go.Bar(name='victory', x=df2['year_week'], y=df2['wins']),
go.Bar(name='defeat', x=df2['year_week'], y=df2['losses'])])



fig.update_layout(barmode='group')
fig.show()

关于python - 如何更改时间序列的条形大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44044754/

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