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).
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."
In Matplotlib, RGB (Red, Green, Blue) is one way to define colors. We can specify RGB colors using either a
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)
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.
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"
Here, "#800080"
is the hex representation of purple, with "80"
for red, "00"
for green, and "80"
for blue.
In Matplotlib, we can also specify colors using predefined names, making it more convenient and human-readable.
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'
Matplotlib supports a broad spectrum of colors based on the
color = 'MediumAquaMarine'
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 matplotlibprint(matplotlib.colors.CSS4_COLORS.keys())
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'
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'
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
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' # Redalpha = 0.5 # 50% transparency
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 pltimport numpy as np# Generating example datat = 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 axesfig, ax = plt.subplots()# Setting different styles and colorsax.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 transparencyax.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 dataplt.legend(facecolor = (0.9, 0.9, 0.9))# Save the plotplt.savefig("/usercode/output/out.png")
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.
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.
Haven’t found what you were looking for? Contact Us
Free Resources