-2

I have a vector x to be plotted, and I want to change the line color depending on the values of a different vector s. Both vectors are the same length, and s only contains 0s and 1s.

I have tried creating a color object such as colors = ['red' if i < 0.5 else 'blue' for i in s], but i get a typeValue error message.

This is what I have:

x, s = hmm.rand(500)
plt.figure(figsize=(10,5))
colors = ['red' if i < 0.5 else 'blue' for i in s]
plt.plot(x[0,0,:], color=colors)
plt.xlabel("t")
plt.ylabel("X[t]")
plt.title("Example output over 500 states")
plt.show()
help
  • 1

1 Answers1

1

If the "color vector" is not well behaved, the line colored according to it is usually unpleasant, and imho this unpleasantness is exactly what you'd get with a boolean vector.

I'd suggest using a line plot plus a scatter plot...

enter image description here

import matplotlib.pyplot as plt
import numpy as np

N = 101
x = np.linspace(0, 10, N)
y = np.sin(x)

np.random.seed(20230423)
s = np.random.choice((0, 1), N)
z = s==0

plt.figure(figsize=(10, 4))
plt.plot(x, y)
plt.scatter(x[ z], y[ z], s=10, color='k', label='s=0')
plt.scatter(x[~z], y[~z], s=10, color='r', label='s=1')
plt.legend()
plt.show()
gboffi
  • 22,939
  • 8
  • 54
  • 85