visuals.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. import pandas as pd
  2. import numpy as np
  3. import statsmodels.api as sm
  4. from sklearn.linear_model import LinearRegression
  5. from sklearn.metrics import mean_squared_error
  6. from scipy import stats
  7. import plotly.graph_objs as go
  8. import cufflinks
  9. cufflinks.go_offline()
  10. def make_hist(df, x, category=None):
  11. """
  12. Make an interactive histogram, optionally segmented by `category`
  13. :param df: dataframe of data
  14. :param x: string of column to use for plotting
  15. :param category: string representing column to segment by
  16. :return figure: a plotly histogram to show with iplot or plot
  17. """
  18. if category is not None:
  19. data = []
  20. for name, group in df.groupby(category):
  21. data.append(go.Histogram(dict(x=group[x], name=name)))
  22. else:
  23. data = [go.Histogram(dict(x=df[x]))]
  24. layout = go.Layout(
  25. yaxis=dict(title="Count"),
  26. xaxis=dict(title=x.replace('_', ' ').title()),
  27. title=f"{x.replace('_', ' ').title()} Distribution by {category.replace('_', ' ').title()}"
  28. if category
  29. else f"{x.replace('_', ' ').title()} Distribution",
  30. )
  31. figure = go.Figure(data=data, layout=layout)
  32. return figure
  33. def make_cum_plot(df, y, category=None, ranges=False):
  34. """
  35. Make an interactive cumulative plot, optionally segmented by `category`
  36. :param df: dataframe of data, must have a `published_date` column
  37. :param y: string of column to use for plotting or list of two strings for double y axis
  38. :param category: string representing column to segment by
  39. :param ranges: boolean for whether to add range slider and range selector
  40. :return figure: a plotly plot to show with iplot or plot
  41. """
  42. if category is not None:
  43. data = []
  44. for i, (name, group) in enumerate(df.groupby(category)):
  45. group.sort_values("published_date", inplace=True)
  46. data.append(
  47. go.Scatter(
  48. x=group["published_date"],
  49. y=group[y].cumsum(),
  50. mode="lines+markers",
  51. text=group["title"],
  52. name=name,
  53. marker=dict(size=10, opacity=0.8,
  54. symbol=i + 2),
  55. )
  56. )
  57. else:
  58. df.sort_values("published_date", inplace=True)
  59. if len(y) == 2:
  60. data = [
  61. go.Scatter(
  62. x=df["published_date"],
  63. y=df[y[0]].cumsum(),
  64. name=y[0].title(),
  65. mode="lines+markers",
  66. text=df["title"],
  67. marker=dict(size=10, color='blue', opacity=0.6, line=dict(color='black'),
  68. )),
  69. go.Scatter(
  70. x=df["published_date"],
  71. y=df[y[1]].cumsum(),
  72. yaxis='y2',
  73. name=y[1].title(),
  74. mode="lines+markers",
  75. text=df["title"],
  76. marker=dict(size=10, color='red', opacity=0.6, line=dict(color='black'),
  77. )),
  78. ]
  79. else:
  80. data = [
  81. go.Scatter(
  82. x=df["published_date"],
  83. y=df[y].cumsum(),
  84. mode="lines+markers",
  85. text=df["title"],
  86. marker=dict(size=12, color='blue', opacity=0.6, line=dict(color='black'),
  87. ),
  88. )
  89. ]
  90. if len(y) == 2:
  91. layout = go.Layout(
  92. xaxis=dict(title="Published Date", type="date"),
  93. yaxis=dict(title=y[0].replace('_', ' ').title(), color='blue'),
  94. yaxis2=dict(title=y[1].replace('_', ' ').title(), color='red',
  95. overlaying='y', side='right'),
  96. font=dict(size=14),
  97. title=f"Cumulative {y[0].title()} and {y[1].title()}",
  98. )
  99. else:
  100. layout = go.Layout(
  101. xaxis=dict(title="Published Date", type="date"),
  102. yaxis=dict(title=y.replace('_', ' ').title()),
  103. font=dict(size=14),
  104. title=f"Cumulative {y.replace('_', ' ').title()} by {category.replace('_', ' ').title()}"
  105. if category is not None
  106. else f"Cumulative {y.replace('_', ' ').title()}",
  107. )
  108. # Add a rangeselector and rangeslider for a data xaxis
  109. if ranges:
  110. rangeselector = dict(
  111. buttons=list(
  112. [
  113. dict(count=1, label="1m", step="month", stepmode="backward"),
  114. dict(count=6, label="6m", step="month", stepmode="backward"),
  115. dict(count=1, label="1y", step="year", stepmode="backward"),
  116. dict(step="all"),
  117. ]
  118. )
  119. )
  120. rangeslider = dict(visible=True)
  121. layout["xaxis"]["rangeselector"] = rangeselector
  122. layout["xaxis"]["rangeslider"] = rangeslider
  123. layout['width'] = 1000
  124. layout['height'] = 600
  125. figure = go.Figure(data=data, layout=layout)
  126. return figure
  127. def make_scatter_plot(df, x, y, fits=None, xlog=False, ylog=False, category=None, scale=None, sizeref=2, annotations=None, ranges=False, title_override=None):
  128. """
  129. Make an interactive scatterplot, optionally segmented by `category`
  130. :param df: dataframe of data
  131. :param x: string of column to use for xaxis
  132. :param y: string of column to use for yaxis
  133. :param fits: list of strings of fits
  134. :param xlog: boolean for making a log xaxis
  135. :param ylog boolean for making a log yaxis
  136. :param category: string representing categorical column to segment by, this must be a categorical
  137. :param scale: string representing numerical column to size and color markers by, this must be numerical data
  138. :param sizeref: float or integer for setting the size of markers according to the scale, only used if scale is set
  139. :param annotations: text to display on the plot (dictionary)
  140. :param ranges: boolean for whether to add a range slider and selector
  141. :param title_override: String to override the title
  142. :return figure: a plotly plot to show with iplot or plot
  143. """
  144. if category is not None:
  145. title = f"{y.replace('_', ' ').title()} vs {x.replace('_', ' ').title()} by {category.replace('_', ' ').title()}"
  146. data = []
  147. for i, (name, group) in enumerate(df.groupby(category)):
  148. data.append(go.Scatter(x=group[x],
  149. y=group[y],
  150. mode='markers',
  151. text=group['title'],
  152. name=name,
  153. marker=dict(size=8, symbol=i + 2)))
  154. else:
  155. if scale is not None:
  156. title = f"{y.replace('_', ' ').title()} vs {x.replace('_', ' ').title()} Scaled by {scale.title()}"
  157. data = [go.Scatter(x=df[x],
  158. y=df[y],
  159. mode='markers',
  160. text=df['title'], marker=dict(size=df[scale],
  161. line=dict(color='black', width=0.5), sizemode='area', sizeref=sizeref, opacity=0.8,
  162. colorscale='Viridis', color=df[scale], showscale=True, sizemin=2))]
  163. else:
  164. df.sort_values(x, inplace=True)
  165. title = f"{y.replace('_', ' ').title()} vs {x.replace('_', ' ').title()}"
  166. data = [go.Scatter(x=df[x],
  167. y=df[y],
  168. mode='markers',
  169. text=df['title'], marker=dict(
  170. size=12, color='blue', opacity=0.8, line=dict(color='black')),
  171. name='observations')]
  172. if fits is not None:
  173. for fit in fits:
  174. data.append(go.Scatter(x=df[x], y=df[fit], text=df['title'],
  175. mode='lines+markers', marker=dict
  176. (size=8, opacity=0.6),
  177. line=dict(dash='dash'), name=fit))
  178. title += ' with Fit'
  179. layout = go.Layout(annotations=annotations,
  180. xaxis=dict(title=x.replace('_', ' ').title() + (' (log scale)' if xlog else ''),
  181. type='log' if xlog else None),
  182. yaxis=dict(title=y.replace('_', ' ').title() + (' (log scale)' if ylog else ''),
  183. type='log' if ylog else None),
  184. font=dict(size=14),
  185. title=title if title_override is None else title_override,
  186. )
  187. # Add a rangeselector and rangeslider for a data xaxis
  188. if ranges:
  189. rangeselector = dict(
  190. buttons=list(
  191. [
  192. dict(count=1, label="1m", step="month", stepmode="backward"),
  193. dict(count=6, label="6m", step="month", stepmode="backward"),
  194. dict(count=1, label="1y", step="year", stepmode="backward"),
  195. dict(step="all"),
  196. ]
  197. )
  198. )
  199. rangeslider = dict(visible=True)
  200. layout["xaxis"]["rangeselector"] = rangeselector
  201. layout["xaxis"]["rangeslider"] = rangeslider
  202. layout['width'] = 1000
  203. layout['height'] = 600
  204. figure = go.Figure(data=data, layout=layout)
  205. return figure
  206. def make_linear_regression(df, x, y, intercept_0):
  207. """
  208. Create a linear regression, either with the intercept set to 0 or
  209. the intercept allowed to be fitted
  210. :param df: dataframe with data
  211. :param x: string or list of stringsfor the name of the column with x data
  212. :param y: string for the name of the column with y data
  213. :param intercept_0: boolean indicating whether to set the intercept to 0
  214. """
  215. if isinstance(x, list):
  216. lin_model = LinearRegression()
  217. lin_model.fit(df[x], df[y])
  218. slopes, intercept, = lin_model.coef_, lin_model.intercept_
  219. df['predicted'] = lin_model.predict(df[x])
  220. r2 = lin_model.score(df[x], df[y])
  221. rmse = np.sqrt(mean_squared_error(
  222. y_true=df[y], y_pred=df['predicted']))
  223. equation = f'{y.replace("_", " ")} ='
  224. names = ['r2', 'rmse', 'intercept']
  225. values = [r2, rmse, intercept]
  226. for i, (p, s) in enumerate(zip(x, slopes)):
  227. if (i + 1) % 3 == 0:
  228. equation += f'<br>{s:.2f} * {p.replace("_", " ")} +'
  229. else:
  230. equation += f' {s:.2f} * {p.replace("_", " ")} +'
  231. names.append(p)
  232. values.append(s)
  233. equation += f' {intercept:.2f}'
  234. annotations = [dict(x=0.4 * df.index.max(), y=0.9 * df[y].max(), showarrow=False,
  235. text=equation,
  236. font=dict(size=10))]
  237. df['index'] = list(df.index)
  238. figure = make_scatter_plot(df, x='index', y=y, fits=[
  239. 'predicted'], annotations=annotations)
  240. summary = pd.DataFrame({'name': names, 'value': values})
  241. else:
  242. if intercept_0:
  243. lin_reg = sm.OLS(df[y], df[x]).fit()
  244. df['fit_values'] = lin_reg.fittedvalues
  245. summary = lin_reg.summary()
  246. slope = float(lin_reg.params)
  247. equation = f"${y.replace('_', ' ')} = {slope:.2f} * {x.replace('_', ' ')}$"
  248. else:
  249. lin_reg = stats.linregress(df[x], df[y])
  250. intercept, slope = lin_reg.intercept, lin_reg.slope
  251. params = ['pvalue', 'rvalue', 'slope', 'intercept']
  252. values = []
  253. for p in params:
  254. values.append(getattr(lin_reg, p))
  255. summary = pd.DataFrame({'param': params, 'value': values})
  256. df['fit_values'] = df[x] * slope + intercept
  257. equation = f"${y.replace('_', ' ')} = {slope:.2f} * {x.replace('_', ' ')} + {intercept:.2f}$"
  258. annotations = [dict(x=0.75 * df[x].max(), y=0.9 * df[y].max(), showarrow=False,
  259. text=equation,
  260. font=dict(size=32))]
  261. figure = make_scatter_plot(
  262. df, x=x, y=y, fits=['fit_values'], annotations=annotations)
  263. return figure, summary
  264. def make_poly_fits(df, x, y, degree=6):
  265. """
  266. Generate fits and make interactive plot with fits
  267. :param df: dataframe with data
  268. :param x: string representing x data column
  269. :param y: string representing y data column
  270. :param degree: integer degree of fits to go up to
  271. :return fit_stats: dataframe with information about fits
  272. :return figure: interactive plotly figure that can be shown with iplot or plot
  273. """
  274. # Don't want to alter original data frame
  275. df = df.copy()
  276. fit_list = []
  277. rmse = []
  278. fit_params = []
  279. # Make each fit
  280. for i in range(1, degree + 1):
  281. fit_name = f'fit degree = {i}'
  282. fit_list.append(fit_name)
  283. z, res, *rest = np.polyfit(df[x], df[y], i, full=True)
  284. fit_params.append(z)
  285. df.loc[:, fit_name] = np.poly1d(z)(df[x])
  286. rmse.append(np.sqrt(res[0]))
  287. fit_stats = pd.DataFrame(
  288. {'fit': fit_list, 'rmse': rmse, 'params': fit_params})
  289. figure = make_scatter_plot(df, x=x, y=y, fits=fit_list)
  290. return figure, fit_stats
  291. def make_extrapolation(df, y, years, degree=4):
  292. """
  293. Extrapolate `y` into the future `years` with `degree` polynomial fit
  294. :param df: dataframe of data
  295. :param y: string of column to extrapolate
  296. :param years: number of years to extrapolate into the future
  297. :param degree: integer degree of polynomial fit
  298. :return figure: plotly figure for display using iplot or plot
  299. :return future_df: extrapolated numbers into the future
  300. """
  301. df = df.copy()
  302. x = 'days_since_start'
  303. df['days_since_start'] = (
  304. (df['published_date'] - df['published_date'].min()).
  305. dt.total_seconds() / (3600 * 24)).astype(int)
  306. cumy = f'cum_{y}'
  307. df[cumy] = df.sort_values(x)[y].cumsum()
  308. figure, summary = make_poly_fits(df, x, cumy, degree=degree)
  309. min_date = df['published_date'].min()
  310. max_date = df['published_date'].max()
  311. date_range = pd.date_range(start=min_date,
  312. end=max_date + pd.Timedelta(days=int(years * 365)))
  313. future_df = pd.DataFrame({'date': date_range})
  314. future_df[x] = (
  315. (future_df['date'] - future_df['date'].min()).
  316. dt.total_seconds() / (3600 * 24)).astype(int)
  317. newcumy = f'cumulative_{y}'
  318. future_df = future_df.merge(df[[x, cumy]], on=x, how='left').\
  319. rename(columns={cumy: newcumy})
  320. z = np.poly1d(summary.iloc[-1]['params'])
  321. pred_name = f'predicted_{y}'
  322. future_df[pred_name] = z(future_df[x])
  323. future_df['title'] = ''
  324. last_date = future_df.loc[future_df['date'].idxmax()]
  325. prediction_text = (
  326. f"On {last_date['date'].date()} the {y} will be {float(last_date[pred_name]):,.0f}.")
  327. annotations = [dict(x=future_df['date'].quantile(0.4),
  328. y=0.8 * future_df[pred_name].max(), text=prediction_text, showarrow=False,
  329. font=dict(size=16))]
  330. title_override = f'{y.replace("_", " ").title()} with Extrapolation {years} Years into the Future'
  331. figure = make_scatter_plot(future_df, 'date', newcumy, fits=[
  332. pred_name], annotations=annotations, ranges=True, title_override=title_override)
  333. return figure, future_df