17.7 C
London
Friday, May 16, 2025
HomePythonMatplotlib in PythonHow to Generate Random Colors in Matplotlib Plots

How to Generate Random Colors in Matplotlib Plots

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the following basic syntax to generate random colors in Matplotlib plots:

1. Generate Random Color for Line Plot

col = (np.random.random(), np.random.random(), np.random.random())

plt.plot(x, y, c=col)

2. Generate Random Colors for Scatterplot

plt.scatter(x, y, c=np.random.rand(len(x),3))

The following examples show how to use this syntax in practice.

Example 1: Generate Random Color for Line Plot

The following code shows how to generate a random color for a single line in a line plot:

import matplotlib.pyplot as plt
import numpy as np

#define data
x = [1, 2, 3, 4, 5]
y = [7, 12, 15, 19, 25]

#define random color
col = (np.random.random(), np.random.random(), np.random.random())

#create line plot with random color
plt.plot(x, y, c=col) 

If we run this exact same piece of code again, a line plot with a different random color will be created:

Example 2: Generate Random Colors for Scatterplot

The following code shows how to create a scatterplot with random colors for each point in the plot:

import matplotlib.pyplot as plt
import numpy as np

#define data
x = [1, 2, 3, 4, 5]
y = [7, 12, 15, 19, 25]

#create scatterplot with random colors for each point
plt.scatter(x, y, c=np.random.rand(len(x),3))

If we run this exact same piece of code again, a scatterplot with new random colors for each point will be created:

Note: Under the hood, this code is simply using NumPy to generate random (R,G,B) colors.

Refer to the online documentation for a complete explanation of the NumPy random() function.

Additional Resources

The following tutorials explain how to perform other common plotting functions in Matplotlib:

How to Change Background Color in Matplotlib
How to Color a Scatterplot by Value in Matplotlib

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories