Color Systems in Matplotlib
Learn how Matplotlib represents colors using named colors, RGB, RGBA, hexadecimal values, color palettes, and colormaps. Understand how to select and apply colors to create meaningful and professional data visualizations.
1. Learning Objectives
After completing this lesson, you will be able to:
- Understand color systems in Matplotlib.
- Use predefined named colors.
- Understand RGB and RGBA color models.
- Apply hexadecimal color codes.
- Use custom color combinations in charts.
- Understand colormaps and their categories.
- Apply sequential, diverging, and qualitative colormaps.
- Use color palettes for multiple data series.
- Choose suitable colors for data visualization.
2. Introduction to Color Systems
Colors are an important part of data visualization. They help users identify different data series, compare values, highlight important information, and understand patterns in charts.
Matplotlib supports multiple ways to specify colors. You can use simple color names, shorthand characters, RGB values, RGBA values, hexadecimal codes, and predefined colormaps.
Why Are Color Systems Important?
Consider a chart that displays sales for five different products. If every line uses the same color, it becomes difficult to identify individual products. Different colors make the chart easier to understand.
Common Color Systems
| Color System | Description |
|---|---|
| Named Colors | Uses predefined color names such as red, blue, and green. |
| RGB | Defines colors using red, green, and blue components. |
| RGBA | Uses red, green, blue, and alpha transparency. |
| Hexadecimal | Represents colors using hexadecimal notation. |
| Colormaps | Maps numerical values to colors. |
3. Using Named Colors
Matplotlib supports many predefined color names. You can
directly pass a color name to the color parameter
when creating a plot.
Common Named Colors
Examples of named colors available in Matplotlib.
Example: Using Named Colors
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
plt.plot(x, [10, 20, 30, 40, 50],
color="red", label="Red")
plt.plot(x, [15, 25, 35, 45, 55],
color="blue", label="Blue")
plt.plot(x, [20, 30, 40, 50, 60],
color="green", label="Green")
plt.title("Named Colors Example")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.legend()
plt.show()
Expected Output
Chart Title: Named Colors Example
Three Lines:
Red Line
Blue Line
Green Line
Legend:
Red
Blue
Green
4. RGB Color System
RGB stands for Red, Green, and Blue. It is a color model that creates different colors by combining these three components.
In Matplotlib, RGB colors can be represented using a tuple of three values. Each value normally ranges from 0 to 1.
RGB Color Structure
RGB colors are created by combining red, green, and blue components.
RGB Value Examples
| RGB Tuple | Color |
|---|---|
(1, 0, 0) |
Red |
(0, 1, 0) |
Green |
(0, 0, 1) |
Blue |
(1, 1, 0) |
Yellow |
(1, 1, 1) |
White |
(0, 0, 0) |
Black |
(0.5, 0.5, 0.5) |
Gray |
Example: RGB Colors in Matplotlib
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
red_color = (1, 0, 0)
green_color = (0, 1, 0)
blue_color = (0, 0, 1)
plt.plot(x, [10, 20, 30, 40, 50],
color=red_color, label="RGB Red")
plt.plot(x, [15, 25, 35, 45, 55],
color=green_color, label="RGB Green")
plt.plot(x, [20, 30, 40, 50, 60],
color=blue_color, label="RGB Blue")
plt.title("RGB Color Example")
plt.legend()
plt.show()
Expected Output
Chart Title: RGB Color Example
Data Series:
1. Red using (1, 0, 0)
2. Green using (0, 1, 0)
3. Blue using (0, 0, 1)
Three colored lines are displayed
with their respective legend entries.
5. RGBA Color System
RGBA stands for Red, Green, Blue, and Alpha. It extends the RGB color system by adding an alpha component that controls transparency.
The first three values define the color. The fourth value controls how transparent or opaque that color appears.
RGBA Structure
color = (red, green, blue, alpha)
| Component | Purpose | Range |
|---|---|---|
| Red | Red color intensity. | 0 to 1 |
| Green | Green color intensity. | 0 to 1 |
| Blue | Blue color intensity. | 0 to 1 |
| Alpha | Transparency level. | 0 to 1 |
Alpha Value Reference
Alpha determines the transparency of an RGBA color.
Example: RGBA Color
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
transparent_red = (1, 0, 0, 0.3)
opaque_blue = (0, 0, 1, 1)
plt.plot(
x,
[10, 20, 30, 40, 50],
color=transparent_red,
linewidth=5,
label="Transparent Red"
)
plt.plot(
x,
[15, 25, 35, 45, 55],
color=opaque_blue,
linewidth=5,
label="Opaque Blue"
)
plt.title("RGBA Color Example")
plt.legend()
plt.show()
Expected Output
Chart Title: RGBA Color Example
First Line:
Red with alpha 0.3.
Second Line:
Blue with alpha 1.0.
The red line appears transparent,
while the blue line appears opaque.
6. Hexadecimal Color Codes
Hexadecimal color codes are another way to specify colors
in Matplotlib. A hexadecimal color code begins with the
# symbol and contains six hexadecimal digits.
The six digits represent three color components: red, green, and blue.
Hexadecimal Structure
A six-digit hexadecimal color code contains red, green, and blue components.
Common Hexadecimal Colors
| Hex Code | Color |
|---|---|
#FF0000 | Red |
#00FF00 | Green |
#0000FF | Blue |
#FFFF00 | Yellow |
#000000 | Black |
#FFFFFF | White |
#FF5733 | Orange-red |
#800080 | Purple |
Example: Using Hexadecimal Colors
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
plt.plot(
x,
[10, 20, 30, 40, 50],
color="#FF5733",
linewidth=3,
label="Orange Red"
)
plt.plot(
x,
[15, 25, 35, 45, 55],
color="#800080",
linewidth=3,
label="Purple"
)
plt.title("Hexadecimal Color Example")
plt.legend()
plt.show()
Expected Output
Chart Title: Hexadecimal Color Example
First Line:
Hex Color #FF5733
Second Line:
Hex Color #800080
Legend:
Orange Red
Purple
7. Working with Color Palettes
A color palette is a collection of colors selected to work together. Color palettes are useful when a chart contains multiple categories or data series.
You can create your own palette using a Python list and apply each color to a different data series.
Example: Custom Color Palette
import matplotlib.pyplot as plt
colors = [
"#2563EB",
"#16A34A",
"#F97316",
"#A855F7",
"#DC2626"
]
months = [1, 2, 3, 4, 5]
data = [
[10, 20, 30, 40, 50],
[15, 25, 35, 45, 55],
[20, 30, 40, 50, 60],
[25, 35, 45, 55, 65],
[30, 40, 50, 60, 70]
]
for i, values in enumerate(data):
plt.plot(
months,
values,
color=colors[i],
label=f"Series {i + 1}"
)
plt.title("Custom Color Palette")
plt.xlabel("Month")
plt.ylabel("Values")
plt.legend()
plt.show()
Expected Output
Chart Title: Custom Color Palette
Five Data Series:
Series 1: Blue
Series 2: Green
Series 3: Orange
Series 4: Purple
Series 5: Red
Each series uses a different palette color.
8. Introduction to Colormaps
A colormap is a predefined mapping between numerical values and colors. It allows Matplotlib to represent different numerical values using different colors.
Colormaps are especially useful for heatmaps, images, scatter plots, contour plots, and other visualizations involving continuous numerical values.
How Colormaps Work
A continuous colormap assigns colors to different numerical values.
Common Matplotlib Colormaps
| Colormap | Description |
|---|---|
viridis | Dark purple through green to yellow. |
plasma | Dark purple through pink to yellow. |
inferno | Dark colors progressing to bright yellow. |
magma | Dark purple progressing to light colors. |
cividis | Blue to yellow, designed for accessibility. |
coolwarm | Blue to neutral to red. |
Greys | Grayscale color mapping. |
turbo | High-contrast multicolor mapping. |
9. Categories of Colormaps
Matplotlib provides different categories of colormaps. Choosing the correct category depends on the type of information you want to communicate.
9.1 Sequential Colormaps
Sequential colormaps are used when numerical data moves from low values to high values. The colors generally progress from lighter to darker or darker to lighter.
Examples: viridis, plasma, inferno, magma.
Sequential color progression.
9.2 Diverging Colormaps
Diverging colormaps are useful when data contains a meaningful central value, such as zero or an average. Colors move away from a central neutral color in two different directions.
Examples: coolwarm, RdBu, seismic.
Diverging colors with a central reference value.
9.3 Qualitative Colormaps
Qualitative colormaps are used to represent different categories or groups. Each category receives a distinct color rather than representing a numerical progression.
Examples: tab10, tab20, Set1, Pastel1.
Qualitative colors for separate categories.
10. Using Colormaps in Scatter Plots
Colormaps can be applied to scatter plots using the
c parameter and the cmap parameter.
The c parameter supplies values used to determine
the colors of individual points.
Example: Scatter Plot with Colormap
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6, 7, 8]
y = [10, 15, 13, 20, 25, 22, 30, 35]
values = [10, 20, 30, 40, 50, 60, 70, 80]
scatter = plt.scatter(
x,
y,
c=values,
cmap="viridis",
s=100
)
plt.colorbar(scatter, label="Data Values")
plt.title("Scatter Plot with Colormap")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.show()
Expected Output
Chart Title: Scatter Plot with Colormap
Plot Type:
Scatter Plot
Markers:
Eight data points.
Colormap:
viridis
Colorbar:
Displays the numerical color scale.
Point Colors:
Different colors represent different data values.
11. Applying Colormaps to Image Data
Matplotlib's imshow() function displays image-like
two-dimensional data. You can apply a colormap to represent
the numerical values in the data using different colors.
Example: Displaying Data with a Colormap
import matplotlib.pyplot as plt
import numpy as np
data = np.array([
[10, 20, 30, 40],
[20, 30, 40, 50],
[30, 40, 50, 60],
[40, 50, 60, 70]
])
image = plt.imshow(
data,
cmap="plasma"
)
plt.colorbar(image, label="Values")
plt.title("Colormap Image Example")
plt.show()
Expected Output
Chart Title: Colormap Image Example
Image:
A 4 x 4 numerical data grid.
Colormap:
plasma
Colorbar:
Displays the numerical value range.
Each cell receives a color based on its value.
12. Listing Available Colormaps
Matplotlib provides many built-in colormaps. You can access
available colormap names through plt.colormaps.
Example
import matplotlib.pyplot as plt
available_colormaps = plt.colormaps()
print("Available Colormaps:")
for cmap in available_colormaps:
print(cmap)
Expected Output
Available Colormaps:
magma
inferno
plasma
viridis
cividis
twilight
twilight_shifted
turbo
coolwarm
bwr
seismic
Greys
Blues
Greens
Reds
Purples
Oranges
...
The complete list depends on the
installed Matplotlib version.
plt.colormaps() to
inspect available colormap names in your installed version
of Matplotlib.
13. Reversing a Colormap
Matplotlib supports reversed versions of built-in colormaps.
You can reverse a colormap by adding _r to its name.
Example
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]
values = [10, 20, 30, 40, 50]
plt.scatter(
x,
y,
c=values,
cmap="viridis_r",
s=150
)
plt.colorbar(label="Values")
plt.title("Reversed Viridis Colormap")
plt.show()
Expected Output
Chart Title: Reversed Viridis Colormap
Plot Type:
Scatter Plot
Colormap:
viridis_r
Color Mapping:
The original viridis color sequence
is displayed in reverse order.
14. Practical Activity
Task: Create a Student Performance Visualization
Create a scatter plot to represent student performance using marks as numerical values.
Given Data:
students = [1, 2, 3, 4, 5, 6, 7, 8]
marks = [45, 55, 60, 70, 75, 80, 90, 95]
Requirements:
- Create a scatter plot using the student data.
- Use marks as the color values.
- Apply the viridis colormap.
- Set marker size to 150.
- Add a colorbar with the label Student Marks.
- Add a meaningful chart title.
- Add X-axis and Y-axis labels.
- Display the chart using
plt.show().
15. Practice Questions
- What is a color system in Matplotlib?
- What is the RGB color model?
- What is the difference between RGB and RGBA?
- What does the alpha component represent?
- How do you specify a hexadecimal color?
- What is a color palette?
- What is a colormap?
- What is the difference between sequential and diverging colormaps?
- When should qualitative colormaps be used?
- What is the purpose of the cmap parameter?
- How do you display a colorbar?
- How can you reverse a built-in colormap?
- Which function lists available Matplotlib colormaps?
Summary
In this lesson, you learned how Matplotlib uses different color systems to customize data visualizations. You explored named colors, RGB values, RGBA transparency, and hexadecimal color codes to define exact colors for plotted data.
You also learned how to create custom color palettes and apply different colormaps to scatter plots and image data. Sequential colormaps are useful for numerical progressions, diverging colormaps help highlight values around a central reference, and qualitative colormaps distinguish separate categories.
Finally, you explored how to display colorbars, list available
colormaps, and reverse a colormap using the _r
suffix. These techniques help create informative, readable,
and professional Matplotlib visualizations.