Astrid
Astrid

Reputation: 1936

What is this plot called and how to make it in matplotlib?

Suppose I have a graph like this

plot(np.random.rand(10))
pylab.ylim([-0,1.5])

enter image description here

and I have a state sequence as such

In[141]:np.random.randint(5,size=(1, 10))
Out[142]:array([[2, 2, 4, 2, 1, 2, 0, 0, 4, 4]])

I want to superimpose that state sequence on the above plot like this:

State sequence example superimposed on data.

But how does one do this in matplotlib?

To summarise: I want different parts of your plot to have differently coloured background that depends on the state, where each unique state has a unique colour.

Upvotes: 0

Views: 295

Answers (1)

Hannes Ovrén
Hannes Ovrén

Reputation: 21831

To divide your plot into differently colored sections you can use the axvspan function.

This requires that you know the x-coordinate boundaries for your states. Assuming that a state is always L units long, and that STATE_COLOR is a mapping between state number and a matplotlib color ('r', 'k', 'b', ...) then you get the following:

# States and their colors
state_list = [1, 2, 1]
STATE_COLOR = { 1 : 'r', 2 : 'y' }

L = 1.5 # Constant state length

x = np.linspace(0, 4.5)
y = x**2 - 3

# Draw states
for i, state in enumerate(state_list):
    x1 = i * L
    x2 = (i+1) * L
    plt.axvspan(x1, x2, color=STATE_COLOR[state])

# Draw line data
plt.plot(x, y)

Upvotes: 1

Related Questions