Plotly - Histogram bins size to weeks

Viewed 3006

I'm trying to plot a histogram with date data using plotly. I would like to plot it with bin sizes corresponding to weeks, and that doesn't seem to work. I searched for documentation about it but didn't find anything.

Here is the code I have. I tried (line 5): 'D7' and 'W1'. That doesn't work (plotly seems not to recognize argument, and set it to one bin per day). What's strange is that 'M1', 'M3' etc... seem to work

fig = go.Figure(data=[go.Histogram(x=df.col, 
                                   xbins=dict(
                                       start='2018-01-01',
                                       end='2018-12-31',
                                       size='D7'), 
                                   autobinx=False)])
fig.update_layout(
    title=go.layout.Title(
        text="title",
        xref="paper",
        x=0.5
    ),
    xaxis_title_text='xaxis title',
    yaxis_title_text='yaxis title'
)


fig.show()

Would someone have any information about this problem ? Thanks

2 Answers

xbins.size is specified in milliseconds by default. To get weekly bins, set xbins.size to 604800000 (7 days with 86,400,000 milliseconds each).

Plotly provides the format xM to get monthly bins because this use case requires more complicated calculations in the background, as monthly bins do not have a uniform size.

It seems that a resampled data source and a bar plot is what you're really looking for:

Plot:

enter image description here

Here, the source data based on daily observations DatetimeIndex(['2020-01-01', '2020-01-02', ... , '2020-07-18'], have been resampled to show sum per week for a certain stock price.

Code:

# Imports
import pandas as pd
#import matplotlib.pyplot as plt
import numpy as np
import plotly.graph_objects as go
#from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot

# data, random sample to illustrate stocks
np.random.seed(12345)
rows = 200
x = pd.Series(np.random.randn(rows),index=pd.date_range('1/1/2020', periods=rows)).cumsum()
y = pd.Series(x-np.random.randn(rows)*5,index=pd.date_range('1/1/2020', periods=rows))
df = pd.concat([y,x], axis = 1)
df.columns = ['StockA', 'StockB']

# resample daily data to weekly sums
df2=df.reset_index()
df3=df2.resample('W-Mon', on='index').mean()

# build and show plotly plot
fig = go.Figure([go.Bar(x=df3.index, y=df3['StockA'])])
fig.show()

Let me know how this works for you.

Related