Home > Software design >  matplotlib: specify custom colors for line plot of numpy array
matplotlib: specify custom colors for line plot of numpy array

Time:07-19

I have a 2D numpy array (y_array) with 3 columns (and common x values as a list, x_list) and I want to create a plot with each column plotted as a line. I can do this by simply doing matplotlib.pyplot.plot(x_list, y_array) and it works just fine.

However I am struggeling with the colors. I need to assign custom colors to each line. I tried by handing a list of my custom colors to the color=key argument, but apparently it does not take a List and throws a ValueError. I find this particularly odd since giving a list for labels actually does work.

I also thought about creating a custom colormap from my choosen colors, but I do not know how to switch to this colormap when plotting...

What can I do to specify the colors to be used when plotting the array? I would like to avoid iterating over the array columns in a for loop.

Thanks in advance!

Edit: minimal working example: This throws the mentioned ValueError

import matplotlib.pyplot as plt
import numpy as np


if __name__ == '__main__':

    x_list = np.linspace(0, 9, 10)
    y1 = np.random.uniform(10, 19, 10)
    y2 = np.random.uniform(20, 29, 10)
    y3 = np.random.uniform(30, 39, 10)
    y_array = np.column_stack([y1, y2, y3])

    labels = ['A', 'B', 'C']
    # plt.plot(x_list, y_array, label=labels)  # this works just fine
    my_colors = ['steelblue', 'seagreen', 'firebrick']
    plt.plot(x_list, y_array, label=labels, color=my_colors)  # throws ValueError
    plt.legend()

    plt.show()

CodePudding user response:

You can create a custom cycler and use it to define your colors.

You can get more information enter image description here

  • Related