Skip to content

Instantly share code, notes, and snippets.

@justinhchae
Created January 12, 2021 15:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinhchae/1aa16e27cbcae052e25c3c784e483711 to your computer and use it in GitHub Desktop.
Save justinhchae/1aa16e27cbcae052e25c3c784e483711 to your computer and use it in GitHub Desktop.
import pandas as pd
import plotly.graph_objects as go
import plotly_express as px
gitcsv = 'https://raw.githubusercontent.com/justinhchae/medium/main/sample.csv'
df = pd.read_csv(gitcsv, index_col=0)
df['dates'] = pd.to_datetime(df['dates'])
freq='M' # or D or Y
df = df.groupby(['types', pd.Grouper(key='dates', freq=freq)])['types'].agg(['count']).reset_index()
df = df.sort_values(by=['dates', 'count']).reset_index(drop=True)
# group the dataframe
group = df.groupby('types')
# create a blank canvas
fig = go.Figure()
# each group iteration returns a tuple
# (group name, dataframe)
for group_name, df in group:
fig.add_trace(
go.Scatter(
x=df['dates']
, y=df['count']
, fill='tozeroy'
, name=group_name
))
# generate a regression line with px
help_fig = px.scatter(df, x=df['dates'], y=df['count']
, trendline="lowess")
# extract points as plain x and y
x_trend = help_fig["data"][1]['x']
y_trend = help_fig["data"][1]['y']
# add the x,y data as a scatter graph object
fig.add_trace(
go.Scatter(x=x_trend, y=y_trend
, name=str('trend ' + group_name)
, line = dict(width=4, dash='dash')))
transparent = 'rgba(0,0,0,0)'
fig.update_layout(
hovermode='x',
showlegend=True
# , title_text=str('Court Data for ' + str(year))
, paper_bgcolor=transparent
, plot_bgcolor=transparent
, title='Monthly Time Series of A and B with Regression'
)
fig.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment