Created
November 21, 2024 19:07
-
-
Save tomron/dffae6ca7c679094894159b26b1d4d6f to your computer and use it in GitHub Desktop.
Bar Chart based on Storytelling With Data - better bar chart visualization
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 typing import Any | |
import pandas as pd | |
import plotly.graph_objects as go | |
import pandas as pd | |
def barchart( | |
df: pd.DataFrame, x_col: str, y_col: str, | |
title: str | None = None, | |
latent_color : str = 'gray', | |
prominent_color: str = 'orange', | |
prominent_value: Any | None = None, | |
**kwargs: dict, | |
) -> go.Figure: | |
"""_summary_ | |
Args: | |
df (pd.DataFrame): Dataframe to plot | |
x_col (str): Name of x coloumn | |
y_col (str): Name of y coloumn | |
title (str | None, optional): Chart title. Defaults to None. | |
latent_color (str, optional): Color to use for the values we don't want to highlight. Defaults to 'gray'. | |
prominent_color (str, optional): Color to use for the value we want to highlight. Defaults to 'orange'. | |
prominent_value (Any | None, optional): Value of the category we want to highlight. Defaults to None. | |
Returns: | |
go.Figure: Plotly figure object | |
""" | |
colors = (df[x_col] == prominent_value).replace(False, latent_color).replace(True, prominent_color).to_list() | |
fig = go.Figure(data=[ | |
go.Bar( | |
x=df[x_col], | |
y=df[y_col], | |
marker_color=colors | |
)], | |
layout=go.Layout( | |
title=title, | |
xaxis=dict(title=x_col, showgrid=False), | |
yaxis=dict(title=y_col, showgrid=False), | |
plot_bgcolor='white', | |
paper_bgcolor='white' | |
) | |
) | |
fig.update_layout(**kwargs) | |
return fig | |
if __name__ == "__main__": | |
data = {'categories': ['A', 'B', 'C', 'D', 'E'], | |
'values': [23, 45, 56, 78, 90]} | |
df = pd.DataFrame(data) | |
fig = barchart(df, 'categories', 'values', prominent_value='C', title='My Chart', yaxis_showgrid=True) | |
fig.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment