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 :-/

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
WΔ_
  • 1,229
  • 4
  • 20
  • 34
  • 1
    Possible duplicate of [python: how to plot one line in different colors](http://stackoverflow.com/questions/17240694/python-how-to-plot-one-line-in-different-colors) – ImportanceOfBeingErnest Nov 19 '16 at 16:24
  • Look at this question: http://stackoverflow.com/questions/17240694/python-how-to-plot-one-line-in-different-colors Also, there is a matplotlib [example about coloring lines](http://matplotlib.org/examples/pylab_examples/multicolored_line.html) – ImportanceOfBeingErnest Nov 19 '16 at 16:25
  • @ImportanceOfBeingErnest Im just going through the questions you suggested now. – WΔ_ Nov 19 '16 at 16:42

1 Answers1

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

Maximilian Peters
  • 30,348
  • 12
  • 86
  • 99