0

I am unable to plot a variable where the points are coloured by reference to an index. What I ultimately want is the line-segment of each point (connecting to the next point) to be a particular colour. I tried with both Matplotlib and pandas. Each method throws a different error.

Generating a trend-line:

datums = np.linspace(0,10,5)
sinned = np.sin(datums)

plt.plot(sinned)

edgy sin graph

So now we generate a new column of the labels:

sinned['labels'] = np.where((sinned < 0), 1, 2)
print(sinned)

Which generate our final dataset:

          0  labels
0  0.000000       2
1  0.598472       2
2 -0.958924       1
3  0.938000       2
4 -0.544021       1

And now for the plotting attempt:

plt.plot(sinned[0], c = sinned['labels'])

Which results in the error: length of rgba sequence should be either 3 or 4

I also tried setting the labels to be the strings 'r' or 'b', which didn't work either :-/

3

1 Answer 1

1

1 and 2 are not a color, 'b'lue and 'r'ed are used in the example below. You need to plot each separately.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

datums = np.linspace(0,10,5)

sinned = pd.DataFrame(data=np.sin(datums))
sinned['labels'] = np.where((sinned < 0), 'b', 'r')
fig, ax = plt.subplots()

for s in range(0, len(sinned[0]) - 1):
    x=(sinned.index[s], sinned.index[s + 1])
    y=(sinned[0][s], sinned[0][s + 1])
    ax.plot(x, y, c=sinned['labels'][s])
plt.show()

Output

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

Comments

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.