Plot digital buses with matplotlib

93 Views Asked by At

I'd like to plot a digital bus like in the picture Bus diagram

This is a hacky attempt I put together but I was wondering if there is a more "default" kind of plot that I am missing

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np

# Sample data
x = [0, 1, 4, 7]
y = ['000', '001', '111', '111']

# Define the height and the side vertex angle
height = 0.5
angle = 160  # in degrees

# A little trigonometry
angle_rad = np.deg2rad(angle)
base = height / np.tan(angle_rad / 2)

# Plotting the base
fig, ax = plt.subplots(figsize=(15,1))  
for i in range(len(x)-1):
    polygon_width = x[i+1]-x[i]
    polygon = patches.Polygon([[x[i], 0], 
                               [x[i]+base/2, height], 
                               [x[i]+polygon_width-base/2, height], 
                               [x[i+1], 0], 
                               [x[i]+polygon_width-base/2, -height], 
                               [x[i]+base/2, -height]],
                               closed=True, facecolor='white', edgecolor='black')
    ax.add_patch(polygon)
    plt.text(x[i]+polygon_width/2, 0, y[i], ha='center', va='center')

plt.xlim([min(x), max(x)])
plt.ylim([-1.5, 1.5])  
plt.xlabel('Time')
plt.ylabel('Bus bin')
plt.title('Bus vs Time')
plt.yticks([])
plt.show()

This is the result of my code: plot

0

There are 0 best solutions below