Generate random line colors in Matplotlib Python
In this tutorial, we learn to generate random line colors in Matplotlib in Python.
You can check: Plot Multiple lines in Matplotlib
Matplotlib is a data visualizing library in Python which helps us to create 2D and 3D plots of data. We will use random() function to generate random colors.
To install matplotlib library on your local machine, open command prompt / terminal and write:
pip install matplotlib
How to Generate random line colors in Matplotlib
Import libraries
# Import libraries import matplotlib.pyplot as plt import random as random
Define data
# define data x = [2, 4, 6, 8, 10] y = [7, 11, 18, 22, 25]
We will create three color variables using random.random() function. All three color variables are merged into a tuple.
color_1= random.random() color_2= random.random() color_3= random.random() #define random color color = (color_1, color_2, color_3)
plt.plot() will take X and Y coordinates and color function.
#create line plot with random color plt.plot(x, y, c=color)
Combining all code
# Import libraries import matplotlib.pyplot as plt import random as random #define data x = [2, 4, 6, 8, 10] y = [7, 11, 18, 22, 25] color_1= random.random() color_2= random.random() color_3= random.random() #define random color color = (color_1, color_2, color_3) #create line plot with random color plt.plot(x, y, c=color)
Output:
Re-run this code to generate a new random color.
We have successfully generated random line colors using Matplotlib.
Leave a Reply