Created
January 12, 2021 15:41
-
-
Save justinhchae/1aa16e27cbcae052e25c3c784e483711 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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