How can we generate random colors in matplotlib plots?

Generating random colors in matplotlib plots is a process of selecting a random set of colors to assign to different elements in a plot, such as data points, lines, or bars. This can be achieved by using the “random” module in Python to generate a random set of RGB (Red, Green, Blue) values, which can then be passed to the plot function in matplotlib. Another method is to use the “colormap” feature in matplotlib, which allows for a range of predefined color schemes to be randomly selected and applied to the plot. Both of these methods can add an element of visual interest and variety to plots, making them more visually appealing and easier to differentiate between different data points or groups.

Generate Random Colors in Matplotlib Plots


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.pyplotas 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.pyplotas 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 for a complete explanation of the NumPy random() function.

Additional Resources

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

x