Change the line color in Matplotlib

Python

Matplotlib

Line

Change color

Luc B.

Python

Matplotlib

Line Plot

Differentiating data series using colors is fundamental to expressive, clear visualizations. While Matplotlib automatically chooses high contrast colors for your line plots, it's often necessary to manually specify color values.

Code Example

Include a color abbreviation in the format string parameter of plt.plot() to change the line color.

import matplotlib.pyplot as plt
import numpy as np

x_values = np.arange(0, 7)
y_values = np.array([0.27, 0.32, 0.35, 0.49, 0.55, 0.7, 0.95])

# Adjust the line colors here
plt.plot(x_values, y_values, "r")       # Make line red
plt.plot(x_values, y_values + 0.5, "b") # Make line blue
plt.plot(x_values, y_values + 1, "m")   # Make line magenta

plt.legend(['Line 1', 'Line 2', 'Line 3'])
plt.show()

png

The supported color abbreviations are:

'b'   # blue
'g'   # green
'r'   # red
'c'   # cyan
'm'   # magenta
'y'   # yellow
'k'   # black
'w'   # white

For more control over the line color, use the color parameter as described below. To change the color of individual markers instead of uniformily changing the line color, use a scatter plot instead of a line plot.

More Examples

Use the color Parameter

For more control, use the color parameter to plt.plot() instead of the format string. This allows you to pass much more specific color values including hex color codes. Supported values are documented in the matplotlib color docs.

import matplotlib.pyplot as plt

x_values = [1, 2, 3, 4]
y_values = [0.27, 0.32, 0.35, 0.49]

# Adjust the line color here
plt.plot(x_values, y_values, color="#20F216")

plt.show()

png

Object Oriented Interface

The same thing can be accomplished using Matplotlib's object oriented interface with the Axes.plot() method.

fig = plt.figure()
ax = plt.axes()

x_values = np.arange(0, 7)
y_values = np.array([0.27, 0.32, 0.35, 0.49, 0.55, 0.7, 0.95])

# Adjust the line colors here
ax.plot(x_values, y_values, "r")       # Make line red
ax.plot(x_values, y_values + 0.5, "b") # Make line blue
ax.plot(x_values, y_values + 1, "m")   # Make line magenta

plt.show()

png