Home > Software engineering >  How to create a continuous rectangle in python with different colors
How to create a continuous rectangle in python with different colors

Time:07-02

I have a data frame like this:

Start   End   Color
1        2     Blue
3        4     Red
5        6     Grey
7        8     Blue
9       10     Red
11      12     Grey

I want to create a rectangle along X-axis. For every row in dataframe, I want to start the rectangle at the Start column and end at the End column with the color that is mentioned in the color column.

Here is an example image of how my rectangle should look like:

Click here for demo image

CodePudding user response:

You can use Rectangle from Matplotlib for each row in your dataframe and plot them together to make one, continuous rectangle.

Here is how you could do it.

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import pandas as pd

df = pd.DataFrame({'Start': [1, 3, 5, 7, 9, 11],
                   'End': [2, 4, 6, 8, 10, 12],
                   'Color': ['Blue', 'Red', 'Grey', 'Blue', 'Red', 'Grey']})

# Initiate figure
fig, axs = plt.subplots()

for row in df.index:
    # Get x axis value where the Rectangle will start
    x_start = df['Start'][row]
    # How long the rectangle will be
    x_width = abs(df['End'][row] - x_start)   1
    # Note: the  1 is so that the rectangles are continuous, if not, there is a gap in between them due to the
    # 'Start' and 'End' values not overlapping
    # Color of rectangle
    color_rect = df['Color'][row]
    # Make the rectangle
    rect = Rectangle(xy=(x_start, 1),
                         width=x_width,
                         height=0.5,
                         color=color_rect)

    # Add Rectangle to the figure
    axs.add_patch(rect)

axs.set_xlim([0, 15])
axs.set_ylim([0, 3])
plt.show()

enter image description here

For more info, check out the Matplotlib Rectangle Documentation - they have more examples you might find useful.

  • Related