holtzy / data_to_viz

Leading to the dataviz you need
https://www.data-to-viz.com/
MIT License
970 stars 278 forks source link

I would like to add swimmer plot #81

Open nstepka opened 1 year ago

nstepka commented 1 year ago

Here is the code for python, how do I get involved?

import pandas as pd import matplotlib.pyplot as plt

Sample data: Each row represents a subject with a unique ID, start and end time of the event

data = [ {"ID": "A", "start": 0, "end": 12}, {"ID": "B", "start": 2, "end": 14}, {"ID": "C", "start": 4, "end": 20}, {"ID": "D", "start": 6, "end": 22}, {"ID": "E", "start": 8, "end": 28}, ]

Convert the data into a pandas DataFrame

df = pd.DataFrame(data)

Function to create a swimmer plot

def create_swimmer_plot(df, subject_col, start_col, end_col): fig, ax = plt.subplots()

for i, row in df.iterrows():
    subject = row[subject_col]
    start = row[start_col]
    end = row[end_col]
    duration = end - start

    ax.plot([start, end], [i, i], lw=2, marker='o', label=subject)

ax.set_yticks(range(len(df)))
ax.set_yticklabels(df[subject_col])
ax.set_xlabel("Time")
ax.set_ylabel("Subjects")
ax.legend()
plt.show()

Create the swimmer plot

create_swimmer_plot(df, "ID", "start", "end")