cmc/cleberg.net

My personal web garden & blog.

clone: git clone https://gitbay.org/cmc/cleberg.net.git

main: utils/salary_visualization.py · raw

 1"""
 2A file that will visualize salary data from an incoming CSV.
 3
 4This script reads a CSV file containing salary data and visualizes it using
 5plotly.
 6"""
 7
 8import locale
 9
10import pandas as pd
11import plotly.graph_objs as go
12from pandas import read_csv as pd_read_csv
13
14locale.setlocale(locale.LC_ALL, "en_US.UTF-8")
15
16# Read the CSV file
17df = pd_read_csv("~/git/cleberg.net/theme/static/salary.csv")
18
19
20def format_currency(value: float) -> str:
21    """
22    Format values in USD currency format.
23
24    Args:
25        value (float): The value to be formatted.
26
27    Returns:
28        str: The formatted value.
29    """
30    return f"${value:,.2f}"
31
32
33# Reverse the order of the DataFrame
34df = df.iloc[::-1].reset_index(drop=True)
35
36# Calculate the percentage increase
37df["Percentage Increase"] = df["Salary"].pct_change() * 100
38
39
40def create_trace(row: pd.Series) -> go.Scatter:
41    """
42    Create a scatter plot trace for a single row.
43
44    Args:
45        row (pd.Series): The row to be plotted.
46
47    Returns:
48        go.Scatter: The created scatter plot trace.
49    """
50    title_company = f"{row['Title']} ({row['Company']})"
51    salary_formatted = format_currency(row["Salary"])
52    if pd.notna(row["Percentage Increase"]):
53        text = f"{salary_formatted} ({row['Percentage Increase']:.2f}%)"
54    else:
55        text = salary_formatted
56    return go.Scatter(
57        x=[row["Start"], row["End"]],
58        y=[row["Salary"], row["Salary"]],
59        text=[text],
60        mode="lines+text",
61        name=title_company,
62        textposition="top center",
63    )
64
65
66# Initialize the plot
67fig = go.Figure()
68
69# Add each data point as a separate trace to display the text
70for index, df_row in df.iterrows():
71    fig.add_trace(create_trace(df_row))
72
73# Update visual styles of the figure
74fig.update_layout(
75    title="Salary Data Over Time (annualized)",
76    xaxis_title="Time",
77    yaxis_title="Salary",
78    font={"family": "monospace", "size": 16},
79    margin={"l": 50, "r": 50, "t": 50, "b": 100},
80    legend={
81        "orientation": "h",
82        "yanchor": "top",
83        "y": -0.3,
84        "xanchor": "center",
85        "x": 0.5,
86    },
87    height=800,
88)
89
90# Display the plot
91fig.show()