1

If i have a dataset:

import numpy as np
import matplotlib.pyplot as plt
y = np.array([np.random.randn(10) for k in range(100)])
plt.plot(y)

plot of random numbers

And a corresponding vector of categorical values:

x = np.array([['nr1', 'nr2'] for k in range(5)]).reshape(10,1)

How do i color according to whether the y is 'nr1' or 'nr2'? It's also ok if pandas plot() function have an easy way.

It should preferably be scalable so there can be more than two groups in x.

2
  • So, you want to plot y with 2 colors based on x i.e. if x[0] is nr1 then plot y[0] with a particular color, and if x[1] is nr2 then plot y[1] with a different color? Commented Apr 22, 2022 at 10:30
  • Yes exactly. :) Or i guess the color of x[1] for y[:,1] Commented Apr 22, 2022 at 10:32

1 Answer 1

2

Edit: This already includes the comment and is working for any number of categories.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
y = np.array([np.random.randn(6) for k in range(100)])

x = np.array([['nr1', 'nr2', 'n3'] for k in range(2)]).reshape(6)

uniques, inverse = np.unique(x, return_inverse=True)
c = mpl.cm.Set1(inverse)

for i in range(y.shape[1]):
    plt.plot(y[:,i], color=c[i])

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Very nice! I forgot to mention that the number of categories can be any number, so that np.unique(x).shape is unknown

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.