How to change line colors in Matplotlib

Overview

Line colors in the Matplotlib library are used to beautify, differentiate, or give varying color presentations for plots in a single program.

In Matplotlib, colors are represented using short codes. Below are some of the various colors in Matplotlib library with their corresponding codes.

Color

Code

red

r

blue

b

yellow

y

white

w

cyan

c

black

k

green

g

How to use colors in a plot

The steps to take when using a specified color for a line of a plot are listed below:

  1. Import the various modules and libraries you need for the plot: the Matplotlib library matplot, numpy, pyplot.

  2. Create your data set(s) to be plotted.

  3. In the plot() method, after declaring the color parameter, assign it to a color name in full, or you can simply use the code. Take a look at this code below:

    Using the full color name:

    Pyplot.plot(x, y, color='red')
    

    Using the color code:

    Pyplot.plot(x, y, colour='r')
    

    Use whichever one from the above is correct for your situation.

  4. Finally, use the show() method to show your plot.

Example 1: Using the color names

Now, let’s use this to create a program with subplots of different colors using the color names.

import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
fig,axs = plt.subplots(2,2)
# using blue color
axs[0,0].scatter(x, y, color = 'blue')
axs[0,0].set_title('blue colour' )
# using the red color
axs[0,1].scatter(x, y, color = 'red')
axs[0,1].set_title('red colour' )
# using the devault yellow color
axs[1,0].scatter(x, y, color = 'yellow')
axs[1,0].set_title('yellow colour' )
# using the black color
axs[1,1].scatter(x, y, color = 'black')
axs[1,1].set_title('black colour' )
plt.tight_layout()
plt.show()

Example 2: Using the color codes

Now, let’s use this to create a program with subplots of different colors using the color codes.

import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
fig,axs = plt.subplots(2,2)
# using blue color
axs[0,0].scatter(x, y, color = 'b')
axs[0,0].set_title('blue colour' )
# using the red color
axs[0,1].scatter(x, y, color = 'r')
axs[0,1].set_title('red colour' )
# using the yellow color
axs[1,0].scatter(x, y, color = 'y')
axs[1,0].set_title('yellow colour' )
# using the black color
axs[1,1].scatter(x, y, color = 'k')
axs[1,1].set_title('black colour' )
plt.tight_layout()
plt.show()

Note: Use the word color and not colour when writing the code. Also, the parameter, color, can be in their hexadecimal color values. For example, #4CAF50 for green.

Free Resources