0

Hi I am new to python and am running into some trouble plotting some time series data as lines while trying to set the color of each line based on a value associated with each line which is stored in a numpy array, here stored as colorValues.

I have a matrix of data to plot, yValues across their corresponding xValues. I want to set the color of each line based on a value for each stored in an array, colorValues. This is following the example here (where using plt.scatter an array of 0's and 1's is entered for the color values as c=someArray).

import matplotlib.pyplot as plt
import numpy as np

yValues
>>>matrix([[-0.33, -0.93,  0.94, -0.17,  0.62],
           [ 0.06, -0.87,  1.1 , -0.17,  0.12],
           [-0.01, -0.78,  0.88, -0.17,  0.18],
           [-0.19, -0.87,  0.94, -0.56,  0.21],
           [-0.08, -0.72,  0.88, -0.35,  0.15]])

xValues = ['1','2','3','4','5']
colorValues = np.array([1, 1, 1, 0, 0])

plt.plot(xValues, yValues, color=colorValues)
plt.show()

However, when I run the code using color=colorValues or c=colorValues it returns the following error:

ValueError: RGBA sequence should have length 3 or 4
Dale2016
  • 11
  • 3

2 Answers2

1

plot can only take a single color. I suspect what you're trying to do is:

import matplotlib.pyplot as plt
import numpy as np


yValues = np.array(  [[-0.33, -0.93,  0.94, -0.17,  0.62],
                       [ 0.06, -0.87,  1.1 , -0.17,  0.12],
                       [-0.01, -0.78,  0.88, -0.17,  0.18],
                       [-0.19, -0.87,  0.94, -0.56,  0.21],
                       [-0.08, -0.72,  0.88, -0.35,  0.15]]  )

xValues = ['1','2','3','4','5']
colorValues = np.array([1, 1, 1, 0, 0]).astype(float)

for y,c in zip(yValues.T, colorValues):
    plt.plot(xValues, y, color=plt.cm.viridis(c))
plt.show()
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
0

To specify grayscale values, you need to use strings, eg '0.1' or '1.0'. See the documentation on colors

a string representation of a float value in [0, 1] inclusive for gray level (e.g., '0.5')


scatter uses c to map the points onto a colormap. However, you are explicitly defining the color with the color parameter for plot function. If you would like to mimic this behavior, you can make use of colormaps (plt.cm) to extract a color. The values need to be between 0 and 1 (as a number, vs string used earlier for grayscale). Here's an example using the jet colormap:

for y, c in zip(yValues, colorValues):
    plt.plot(xValues, y, color=plt.cm.jet(value))
busybear
  • 10,194
  • 1
  • 25
  • 42
  • Thank you for the reply, but I am not sure what you mean. Running the code on the linked example it produces a plot with data points in two colors, both yellow and blue. Could you be more explicit in what you mean? And why does it work as is for plt.scatter but not plt.plot? – Dale2016 Jan 21 '19 at 20:14