How to specify colors in Matplotlib

Key takeaways:

  • Matplotlib allows specifying colors using RGB values as tuples or hex strings.

  • Predefined color names make it easy to use single-character or case-insensitive X11/CSS4 color names.

  • xkcd and Tableau color schemes offer creative and distinct color palettes for visualizations.

  • Grayscale colors use float values between 0 (black) and 1 (white) for various gray shades.

  • Transparency (alpha) controls color opacity, ranging from 0 (fully transparent) to 1 (fully opaque).

  • Effective use of colors enhances data visualization and improves audience understanding.

Matplotlib is a popular Python library for creating visualizations in various forms, such as charts, plots, and graphs. One crucial aspect of data visualization is choosing the right colors to represent your data effectively. In Matplotlib, we can specify colors in various ways. In this Answer, we will try to explore most of them with the help of some interactive code examples.

Interested in changing line color? Check out our Answer "How to change line colors in Matplotlib."

RGB color definition

In Matplotlib, RGB (Red, Green, Blue) is one way to define colors. We can specify RGB colors using either a tupleA tuple is a finite sequence or an ordered list of numbers. of floats or a case-insensitive hex string.

Tuple of floats

A tuple of three float values in the range [0, 1] represents RGB colors. Each float corresponds to the intensity of the Red, Green, and Blue components, respectively.

For instance, if we want to specify the color purple, we can create a tuple like this:

purple = (0.5, 0, 0.5)
A tuple to define the purple color in RGB format

Here, the first value 0.5 represents the intensity of Red, the second value 0 represents Green, and the third value 0.5 represents Blue.

Case-insensitive hex string

Another way to specify RGB colors is by using a case-insensitive hex string. This string represents the color in hexadecimal format with a # prefix. We have a total of 256 values to choose from for each RGB component. Starting from hexadecimal 0 to hexadecimal ff.

For instance, to specify the color purple, we can use the hex string:

teal = "#800080"
A hex string to define the purple color in RGB format

Here, "#800080" is the hex representation of purple, with "80" for red, "00" for green, and "80" for blue.

Color name definition

In Matplotlib, we can also specify colors using predefined names, making it more convenient and human-readable.

Single character

Matplotlib provides a set of single-character names for basic colors, as shown in the table below.

Character

Color

b

blue

g

green

r

red

c

cyan

m

magenta

y

yellow

k

black

w

white

We can use these single-character color names in plotting functions by providing them as a string. For example:

color = 'r'

From X11/CSS4

Matplotlib supports a broad spectrum of colors based on the X11/CSS4The X11/CSS4 color names are a set of predefined colors used in web development and design. color names. These are case-insensitive, and we can use them to specify colors easily. For example:

color = 'MediumAquaMarine'
An example defining color name using xkcd color scheme

An exhaustive list of X11/CSS4 color names used by Matplotlib can be obtained from the CSS4 color dictionary. The following code does that:

import matplotlib
print(matplotlib.colors.CSS4_COLORS.keys())
Code to obtain CSS4 color names

From xkcd

Matplotlib also offers a collection of colors inspired by the xkcd color survey, which includes a wide range of imaginative color names. We can use these case-insensitive names like this:

color = 'apple green'
An example defining color name using xkcd color scheme

From Tableau Colors

Another set of distinct colors provided by Matplotlib comes from the "T10" categorical palette, which are case-insensitive color names. These are also the default colors used by Matplotlib to categorize data. Here is a list of commonly used colors:

  • 'tab:blue'

  • 'tab:green'

  • 'tab:red'

  • 'tab:brown'

  • 'tab:gray'

We can define these as demonstrated by the following code:

color = 'tab:blue'
An example defining color name using Tableau Color scheme

Grayscale colors

For grayscale colors, we can use a string representation of float values within the closed interval [0, 1]. A value of 0.0 represents black, 1.0 represents white, and values in between represent various shades of gray.

color = '0.8' # A light gray color
An example for the use of grayscale color

Transparency

Transparency, also known as alpha, can be specified in Matplotlib to make colors partially transparent. This improves data visualization when overlapping elements. The alpha value is a float in the range [0, 1], where 0 is fully transparent, and 1 is fully opaque.

color = 'r' # Red
alpha = 0.5 # 50% transparency
An example for the use of transparency

Try it yourself

Whether we prefer specifying colors with RGB values, color names, or adjusting transparency, Matplotlib provides various options to meet our needs. We have supplied a sample code that uses all the color representations discussed above.

Note: You may make the desired changes and explore different color representations offered by Matplotlib.

import matplotlib.pyplot as plt
import numpy as np
# Generating example data
t = np.linspace(0.0, 2.0, 201)
y = np.cos(2 * np.pi * t) # Using a cosine function for different data
# Creating a figure and axes
fig, ax = plt.subplots()
# Setting different styles and colors
ax.set_facecolor('0.95')
ax.set_title('Cosine Wave', color='#800080')
ax.set_xlabel('Time [s]', color='c')
ax.set_ylabel('Amplitude', color='plum')
# Plotting data with various line styles and colors, and adding transparency
ax.plot(t, y, 'xkcd:indigo', alpha=0.5, linewidth = 4, label = "G1")
ax.plot(t, 0.5 * y, color = 'C1', alpha = 0.5, linewidth = 4, label = "G2")
ax.tick_params(labelcolor = 'tab:red')
# Creating legend for the data
plt.legend(facecolor = (0.9, 0.9, 0.9))
# Save the plot
plt.savefig("/usercode/output/out.png")

Code explanation

The explanation of the code demonstrating all different color representations above is as follows:

  • Line 12: A float value is provided as a string to specify the background color.

  • Line 13: A hex string is provided to set the title color.

  • Line 14: A single letter string is provided to set the x-axis label color.

  • Line 15: A color name from the X11/CSS4 scheme is provided to set the y-axis label color.

  • Line 18: A color name from the xkcd color scheme is provided to set the line color, and the transparency is set to 50%.

  • Line 19: A color name from the Cn scheme is provided to set the line color, and the transparency is set to 50%.

  • Line 20: A color name from the tableau scheme is provided to specify the color of the tick labels.

Conclusion

Choosing the right colors is essential for effective data visualization in Matplotlib. Remember to keep the audience in mind and ensure that the chosen colors are not only visually appealing but also enhance the understanding of your data. By understanding the color specification options in Matplotlib, you can create more compelling and informative data visualizations.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How to assign colors in Matplotlib?

You can assign colors using RGB values (tuples or hex strings), predefined color names (X11/CSS4 or xkcd), Tableau colors, or grayscale values (0 for black to 1 for white).


How to set marker color in Matplotlib?

Use the markerfacecolor or markeredgecolor parameters in plotting functions to specify the marker’s fill and edge colors.


How to change background color in matplotlib?

Set the background color using the facecolor parameter in plt.figure() or ax.set_facecolor().


What is the default Matplotlib colors?

Matplotlib uses the Tableau “T10” categorical palette as its default colors. Examples include 'tab:blue', 'tab:orange', and 'tab:green'.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved