Customize the colors of a line plot for a NumPy array using matplotlib

Having a 2D numpy array (y_array) with 3 columns (and shared x values in a list, x_list), I'm looking to plot each column as a line. Using

matplotlib.pyplot.plot(x_list, y_array)
accomplishes this successfully.

The challenge arises when it comes to colors. I wish to assign custom colors to each line. Attempting to pass a list of custom colors to the color= argument results in a ValueError. It's puzzling that while passing a list for labels works fine, colors throw an error.

I've considered generating a custom colormap from my desired colors but struggle with how to apply this colormap during plotting...

Is there a way to specify the colors for plotting the array? Ideally, I'd like to avoid iterating over the array columns in a loop.

Thank you in advance!

Edit: minimal working example: This leads to 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()

Answer №1

If you want to add a personal touch to your color scheme, consider creating your own custom cycle of colors.

For detailed instructions on how to do this, check out the link here

import matplotlib.pyplot as plt
import numpy as np
from cycler import cycler


if __name__ == '__main__':
    my_colors = ['skyblue', 'limegreen', 'tomato']
    custom_cycler = cycler(color=my_colors)
                  
    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])
    
    fig, ax = plt.subplots()
    ax.set_prop_cycle(custom_cycler)
    ax.plot(x_list, y_array)    
    plt.show()

https://i.stack.imgur.com/zpu6t.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the potential of Django to efficiently implement multiple listviews on a single webpage

Recently started working with Python and Django, but I may have bitten off more than I can chew. If anyone has the time to help educate me, I would greatly appreciate it. My main model deals with "work orders," each of which is linked to subsets of data. I ...

Optimal method for shuffling a matrix in either R or Python

Currently, I am dealing with a large numeric matrix M in R that consists of 11000 rows and 20 columns. Within this matrix, I am conducting numerous correlation tests. Specifically, I am using the function cor.test(M[i,], M[j,], method='spearman' ...

Gathering information from a website by using BeautifulSoup in Python

When attempting to scrape data from a table using BeautifulSoup, the issue I'm running into is that the scraped data appears as one long string without any spaces or line breaks. How can this be resolved? The code I am currently using to extract text ...

What is the method for generating a field in a Django model that is based on the values of other fields within the same

In my Django model, I want to add a field named total that will calculate the total price of all products multiplied by their quantity. Can anyone guide me on how to implement this logic: total = price*quantity? Keep in mind that there can be multiple prod ...

Navigating through a multi-level dataframe using Python

I have encountered JSON values within my dataframe and am now attempting to iterate through them. Despite several attempts, I have been unsuccessful in converting the dataframe values into a nested dictionary format that would allow for easier iteration. ...

I am struggling to comprehend the einsum calculation

As I attempt to migrate code from Python to R, I must admit that my knowledge of Python is far less compared to R. I am facing a challenge while trying to understand a complex einsum command in order to translate it. Referring back to an answer in a previ ...

Is there a way to automatically start a process during system boot at runlevel 2 using code?

Can someone please help me figure out how to write Python code that will initiate a process during startup, specifically at level two? I've done some research on my own, but I'm still unsure about the most reliable method to use across different ...

What causes the unrecognized command line error to occur while using distutils to build a C extension?

When attempting to construct a source using the python's distutils, I encountered an issue. I crafted a basic setup.py following guidance from this example, and executing the build as recommended resulted in success: python setup.py build Now, it is ...

Discover all consecutive sequences with a cumulative value of zero

Imagine having an array containing N integers and our goal is to identify all subsequences of consecutive elements with a sum equal to zero. For example: N = 9 array = [1, -2, 4, 5, -7, -4, 8, 3, -7] The expected output should be: 1 4 4 7 5 8 1 8 ...

Setting up your YAML configuration to utilize both PHP and Python with AJAX in a unified project on App Engine

Here is my project idea https://i.stack.imgur.com/oGOam.jpg $.ajax({ url: '../server/python/python_file.py', dataType: 'json', type: 'POST', success:function(data) { //Perform additional AJAX requests using PHP f ...

Here are the steps to resolve the error message: "selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element"

I am currently in the process of learning Selenium. My focus is on creating a script that can add multiple items to a shopping cart. Interestingly, when I removed the class from my script, it allowed me to successfully add an item to the cart. However, on ...

What is preventing this function from displaying the expected output?

def checkStraight(playerHand): playerHand.sort() print(playerHand) for i in range(len(playerHand)-1): if playerHand[i] != playerHand [i+1] - 1: handStrength = 0 return False break else: ...

Is there a division by zero issue in Python?

I'm currently working on a program where the user provides values for variables a, b, c, d, e, and f to calculate and display the result. If ad - bc equals 0, then I need to indicate that there is no solution. However, even with the following code sni ...

When using Python with Selenium, the value of a CSS property may appear differently in the output compared to

I am trying to figure out why all of the properties are returning as normal instead of bold for some text. I was hoping someone could explain to me what is causing this issue and how to fix it. This is my Python code: from selenium import webdriver urls ...

Guidelines for implementing a logout feature in Django using templates

Here is my views.py file: from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt import os # Create your views here. @csrf_exempt def index(request): if('loggedIn' in request.session): id = request. ...

What could be causing my sjoin() function to produce an empty GeoDataFrame?

I'm currently working on a spatial join operation between two GeoDataFrames. The first GeoDataFrame contains the coordinates of points associated with specific names. The second GeoDataFrame consists of polygons derived from the French cadastre data. ...

Error message: Reaching beyond the boundaries of a list when utilizing an if statement in Python

I have a list, text_split = [['5', '5', '12\n'], ['1', '1\n'], ['1', '2\n'], ['2', '1\n'], ['2', '3\n'], ['3', ...

Retrieving HTML content of a scrolled page using Selenium

I am a beginner with Selenium and currently attempting to scroll to the bottom of Twitter profiles in order to access all tweets for web scraping. My goal is to retrieve the HTML content of the fully scrolled page, but I encountered an issue while trying t ...

Is it time to refresh the supervisor's Python instance with Crontab?

Encountering a strange issue while utilizing crontab to restart a supervisor python instance. Here are the specifics: Implemented a basic Python script with some scheduled jobs (apscheduler) The script requires supervision by supervisor, configured it a ...

Organize the individuals in one straight line

While browsing LeetCode, I stumbled upon this interesting question: The task is straightforward - sorting "a list of people" based on their respective heights. After a brief moment of contemplation, I quickly drafted the following code: # Input: names = [ ...