Python – Matplotlib bool diagram rectangle fill

Matplotlib bool diagram rectangle fill… here is a solution to the problem.

Matplotlib bool diagram rectangle fill

I want to create a bool data graph in Matplotlib and Python. I have several bool channels, and if channel = 1 (or true), I want to fill a color

I found it.
this C# question, which pretty much shows the bottom plot I want
this image .

My current idea is to use multiple subgraphs with shared x-axis and use fill_between to fill my channel=1 time.

Before I go ahead and write the code, I’m wondering if there’s already something in Matplotlib that could make this easier? I don’t want to worry about y-values to control height, but rather make it more of a horizontal bar chart, except that my x-axis is a time series and I have gaps in my bars.

Solution

I’ve used the matplotlib > AX.hlines solves this problem.

I also used a function to find the start and end idx of the truth value in the array. I got this from another article on SO, but I can’t find it now!

import numpy as np

def findones(a):
    isone = np.concatenate(([0], a, [0]))
    absdiff = np.abs(np.diff(isone))
    ranges = np.where(absdiff == 1)[0].reshape(-1, 2)
    return np.clip(ranges, 0, len(a) - 1)

def plotbooleans(ax, dictofbool):
    ax.set_ylim([-1, len(dictofbool)])
    ax.set_yticks(np.arange(len(dictofbool.keys())))
    ax.set_yticklabels(dictofbool.keys())

for i, (key, value) in enumerate(dictofbool.items()):
        indexes = findones(value)
        for idx in indexes:
            if idx[0] == idx[1]:
                idx[1] = idx[1]+1
            ax.hlines(y=i, xmin=idx[0], xmax=idx[1], linewidth=10, colors='r')
return ax

Test code:

import matplotlib.pyplot as plt
testarray = np.array([1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1])
testbool = {}
for i in range(0, 5):
    testbool['bool_{}'.format(i)] = testarray
fig, ax = plt.subplots()
ax = plotbooleans(ax, testbool)
plt.grid()
plt.subplots_adjust(bottom=0.2)
plt.show()

The output should look like this:
boolean plot

Related Problems and Solutions