Created
October 13, 2022 23:30
-
-
Save eliasdabbas/e80eeb629d9c8efcf34cdd22ab3ee848 to your computer and use it in GitHub Desktop.
Visualize a list of HTTP status codes as a treemap of two levels.
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
from http.client import responses | |
import pandas as pd | |
import plotly.express as px | |
import dash_bootstrap_components as dbc | |
from dash_bootstrap_templates import load_figure_template | |
themes = [theme for theme in dir(dbc.themes) if theme[0].isupper()] | |
load_figure_template(themes=themes) | |
def status_code_chart( | |
status_list, | |
height=600, | |
theme='none', | |
title='Status Codes', export_to_html=None): | |
"""Create a treemap to visualize a list of status codes. | |
Parameters: | |
----------- | |
status_list : list, tuple, pandas.Series | |
A collection of HTTP status codes | |
height: integer | |
The desired height of figure in pixels | |
theme : str | |
Name of theme to use for the chart. Available themes: | |
bootstrap, cerulean, cosmo, cyborg, darkly, flatly, grid, journal, | |
litera, lumen, lux, materia, minty, morph, pulse, quartz, | |
sandstone, simplex, sketchy, slate, solar, spacelab, superhero, | |
united, vapor, yeti, zephyr | |
title: str | |
The title of the figure | |
export_to_html: str, optional | |
The path to the HTML file if you want to save it | |
""" | |
status_counts = ( | |
pd.Series(status_list) | |
.value_counts() | |
.reset_index() | |
.rename(columns={ | |
'index': 'status', | |
'status': 'count' | |
}) | |
.assign(status_cat=lambda df: df['status'].astype(int).round(-2)) | |
.assign(status_cat_desc=lambda df: [responses[int(code)] for code in df['status_cat']]) | |
.assign(status_desc=lambda df: [responses[int(code)] for code in df['status']])) | |
status_fig = px.treemap( | |
status_counts, | |
maxdepth = 2, | |
path=[px.Constant('Status codes'), 'status_cat', 'status'], | |
hover_name='status_cat', | |
height=height, | |
custom_data=['status_desc', 'status_cat_desc'], | |
values='count', | |
title=title, | |
template=theme.upper()) | |
status_fig.data[0].marker.line.width = 0.01 | |
status_fig.data[0].marker.pad = dict.fromkeys('lrbt', 0) | |
status_fig.data[0]['texttemplate'] = '<b>%{label} </b><br><br>Status code: %{label} %{customdata[0]}<br>Count: %{value:,}<br>%{percentParent:.1%} of %{parent}<br>%{percentRoot:.1%} of %{root}' | |
status_fig.data[0]['hovertemplate'] = '<b>%{label} </b><br><br>Status code: %{label} %{customdata[0]}<br>Count: %{value:,}<br>%{percentParent:.1%} of %{parent}<br>%{percentRoot:.1%} of %{root}' | |
if export_to_html: | |
status_fig.write_html(export_to_html) | |
return status_fig |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Features
status_code_figure.mov