Skip to Content

How to set color bar in matplotlib?

Matplotlib is a popular Python library used for data visualization and plotting. It provides a wide range of customizable plot types and options to create informative and aesthetically pleasing plots. One useful feature in matplotlib is the ability to add color bars to plots. Color bars provide a visual representation of how a color map corresponds to data values. This allows readers to easily interpret the significance of colors in a plot. In this comprehensive guide, we will cover everything you need to know about setting color bars in matplotlib plots.

What is a Color Bar?

A color bar, also known as a colormap legend, is a visual aid that maps data values to colors. It provides a scale that helps readers equate colors to quantities or intensities. The color bar displays a spectrum of colors moving from one end color representing minimum values to another end color representing maximum values. Intermediate values are displayed as blends between the end color shades. This gives a visualization of the color gradient in the plot.

For example, in a plot of elevation data, lower elevations could be colored in blues and higher elevations in yellows and reds. The corresponding color bar would display blue to red spectrum indicating that blue represents low elevations and red represents high elevations. Looking at the color bar gives instant insight into what the different colors signify in the plot. Color bars are extremely useful for interpreting heatmaps, contour plots, pseudocolor plots and other plot types that use a colormap to visually encode values.

When to Use a Color Bar

Color bars provide a legend for the colormap used in a plot. They are most helpful when the plot uses a continuous color mapping to visually represent data values. For example:

  • Heatmaps use color intensity to show magnitude of values, with color bar indicating intensity scale.
  • Contour plots use color shades to distinguish between different numeric contours, with color bar showing value of each color contour.
  • Pseudocolor plots map data values to colors, with color bar displaying color scale.
  • Surface and wireframe plots use color gradients to depict 3D surfaces, with color bar revealing meaning of colors.

If the colors in the plot are not mapped to data values, a color bar may not be useful. For example, in a pie chart with categorical colors or a plot using colors simply to distinguish different lines, a color bar is not necessary.

Anatomy of a Color Bar

A basic vertical color bar consists of:

  • Color spectrum – Displays gradient of colors from low to high values
  • Tick marks – Indicates specific data values corresponding to color shades
  • Tick labels – Labels for the tick marks displaying their numeric values
  • Title – Descriptive title explaining what the color bar represents

The color spectrum visually links data values to colors. The tick marks and labels quantify that linkage. The title describes the significance of the color bar. Similar components are present in horizontal color bars as well.

How to Add a Color Bar to Matplotlib Plots

Matplotlib provides the Colorbar class to easily add color bars to plots. Here are the main steps to add a vertical color bar to an existing matplotlib axes:

  1. Create the plot using a colormap.
  2. Get the colormap used to specify colors.
  3. Create the Colorbar object, specifying the colormap.
  4. Add the color bar to the plot using the matplotlib axes instance.

This adds a default vertical color bar to the plot. Let’s go through an example:

“`python
import matplotlib.pyplot as plt
import numpy as np

# Create data
data = np.random.randn(10,10)

# Plot heatmap using imshow with hot colormap
fig, ax = plt.subplots()
im = ax.imshow(data, cmap=’hot’)

# Get colormap
cmap = im.cmap

# Create colorbar
cbar = fig.colorbar(im, cmap=cmap)

plt.show()
“`

This plots a heatmap of random data and adds a default color bar to it. The key steps are using a colormap, fetching the colormap, creating a Colorbar linked to the image plot, and adding it to the axes subplot. This can be customized further as discussed in following sections.

Vertical Color Bar

The colorbar is added to the same figure as the plot by default. To make the color bar vertical, set the orientation parameter in Colorbar to ‘vertical’:

“`python
cbar = fig.colorbar(im, cmap=cmap, orientation=’vertical’)
“`

Horizontal Color Bar

To create a horizontal color bar below the plot, specify the orientation as ‘horizontal’:

“`python
cbar = fig.colorbar(im, cmap=cmap, orientation=’horizontal’)
“`

Positioning the Color Bar

We can specify the location of the color bar using the ax parameter. For vertical color bar:

“`python
cbar = fig.colorbar(im, cmap=cmap, ax=ax, location=’right’) # Puts color bar to right of plot
“`

For horizontal color bar:

“`python
cbar = fig.colorbar(im, cmap=cmap, ax=ax, orientation=’horizontal’, location=’bottom’) # Puts color bar below plot
“`

This allows positioning the color bar at desired location on the axes subplot.

Customizing the Color Bar

Matplotlib offers extensive customization of color bars to create informative color bars tailored to your data. Here are some useful customizations.

Setting Color Bar Thickness

Use the shrink parameter to adjust thickness of the color bar:

“`python
cbar = fig.colorbar(im, cmap=cmap, shrink=0.6) # Smaller value thickens colorbar
“`

Setting Ticks and Tick Labels

Ticks and tick labels can be explicitly set by passing tick locations and tick labels to Colorbar:

“`python
ticks = [0, 2, 4, 6, 8, 10]
tick_labels = [‘Min’, ‘Low’, ‘Medium’, ‘High’, ‘Max’]

cbar = fig.colorbar(im, cmap=cmap, ticks=ticks, tick_labels=tick_labels)
“`

Adding Title

Title can be added using set_label() method:

“`python
cbar = fig.colorbar(im, cmap=cmap)
cbar.set_label(‘Temperature (°C)’)
“`

Setting Color Limits

The colormap range can be set using vmin and vmax arguments. This adjusts the color spectrum:

“`python
im = ax.imshow(data, cmap=’hot’, vmin=0, vmax=100)
“`

This will map data values between 0 and 100 to the hot colormap.

Using Log Scale

To use a log scale colormap, where equal steps in data are represented by unequal steps in the color map, we can pass norm=LogNorm():

“`python
im = ax.imshow(data, cmap=’hot’, norm=LogNorm())
“`

This maps the data logarithmically to the color map.

Setting Number of Ticks

Use the ticks parameter in Colorbar to set approximate number of ticks:

“`python
cbar = fig.colorbar(im, cmap=cmap, ticks=5) # Sets ~5 tick marks
“`

Formatting Tick Labels

Tick labels can be formatted for a fixed precision using ScalarFormatter:

“`python
import matplotlib.ticker as ticker

formatter = ticker.ScalarFormatter(useMathText=True)
formatter.set_scientific(True)
formatter.set_powerlimits((-2, 2))

cbar = fig.colorbar(im, cmap=cmap)
cbar.locator = ticker.MaxNLocator(5)
cbar.formatter = formatter
cbar.update_ticks()
“`

This formats tick labels in scientific notation with 2 decimal places.

Setting Font Properties

Font properties like font size, weight, family can be set for the tick labels, axis labels and title:

“`python
cbar.ax.tick_params(labelsize=14)
cbar.ax.xaxis.label.set_fontweight(‘bold’)
cbar.ax.set_title(‘Temperature’, fontname=’Times New Roman’, fontsize=16)
“`

This allows styling the font to the desired specifications.

Setting Color Bar Extensions

The color bar length can be increased beyond the plot extent using extend parameter:

“`python
cbar = fig.colorbar(im, cmap=cmap, extend=’both’)
“`

This extends the color bar on both ends, useful when data values are out of plotted range.

Adding Color Bar to Secondary Axes

For plots with multiple y-axes, we can associate the color bar with a particular y-axis by passing the respective axes instance:

“`python
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))

# Plot 1
im1 = ax1.imshow(data1, cmap=’Reds’)
cbar1 = fig.colorbar(im1, ax=ax1)

# Plot 2
im2 = ax2.imshow(data2, cmap=’Blues’)
cbar2 = fig.colorbar(im2, ax=ax2) # Colorbar linked to ax2
“`

This allows having independent color bars for each subplot axes.

Color Bar Best Practices

Here are some tips for effective use of color bars in matplotlib:

  • Only use color bars if colormap is mapped to data values. Avoid in plots with categorical colors.
  • Describe what the color bar represents using a title.
  • Make sure number of ticks and tick labels accurately convey colormap scale.
  • Use extend options if data values fall outside color bar range.
  • Format tick labels appropriately to clearly convey values.
  • Set color bar thickness to stand out but not obscure the plot.
  • Place color bar close to the plot for easy associativity.
  • Make the color bar large enough to be easily readable.
  • Use appropriate colormaps based on data and audience.

Following these best practices will result in informative and visually appealing color bars!

Advanced Color Bar Customization

For greater control, the colorbar can be created directly by instantiating a Colorbar object. This involves creating axes for the colorbar, plotting the colorbar image on it, and adjusting the axes properties. Here is an example:

“`python
import matplotlib as mpl

# Create figure and axes
fig = plt.figure(figsize=(6, 5))
ax = fig.add_subplot(111)

# Generate plot
im = ax.imshow(data, norm=LogNorm(), cmap=’coolwarm’)

# Create new axes for colorbar
cax = fig.add_axes([0.95, 0.2, 0.03, 0.6])

# Create colorbar
norm = mpl.colors.Normalize(vmin=data.min(), vmax=data.max())
cb = mpl.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm)

# Set tick locations and add tick labels
cb.set_ticks([2, 4, 6, 8, 10])
cax.set_yticklabels([‘Low’, ‘Medium’, ‘High’])

# Set color bar title
cb.set_label(‘Colorbar Title’)

plt.show()
“`

This allows fine-grained control over the colorbar properties. However, for most purposes using the simple fig.colorbar() method is recommended.

Colormaps in Matplotlib

The choice of colormap is important for effective visualization. Matplotlib provides a wide range of built-in colormaps to choose from. Some useful colormaps for numeric data are:

  • hot – Black to red spectrum
  • viridis – Blue to yellow spectrum
  • plasma – Blue to red spectrum
  • inferno – Yellow to red spectrum
  • magma – White to red spectrum
  • cividis – Optimized for color vision deficiencies

These provide perceptually uniform gradients good for representing ordered data. Colormaps like jet are not recommended as they can introduce visual artifacts. Qualitative colormaps like tab10 are available for categorical data. The full list of colormaps can be viewed using:

“`python
import matplotlib.pyplot as plt
plt.colormaps()
“`

This displays all available colormap options to select from.

Color Bars in Seaborn

Seaborn is a statistical visualization library built on matplotlib. It also allows adding color bars through the cbar_kws argument:

“`python
import seaborn as sns

# Plot heatmap
heatmap = sns.heatmap(data, cbar_kws={‘label’: ‘Colorbar Title’})

# Access colorbar object
cbar = heatmap.figure.get_axes()[1]

# Customize colorbar ticks, labels, etc
“`

The Seaborn heatmap handles colorbar creation, returning the colorbar axes for further customization.

Color Bars with Pandas and Matplotlib

For data stored in Pandas DataFrames, we can use the DataFrame’s plotting methods to easily create plots with colorbars:

“`python
import pandas as pd
df = pd.DataFrame(data)

# Plot heatmap
ax = df.plot.imshow(cmap=’plasma’)

# Add colorbar
fig = ax.get_figure()
fig.colorbar(ax.collections[0], ax=ax)
“`

This leverages Pandas integration with matplotlib to plot DataFrames with colorbars.

Plotly Colorbars

Plotly is another Python plotting library that supports adding colorbars. Here is an example:

“`python
import plotly.express as px

# Create figure
fig = px.imshow(data, color_continuous_scale=’Viridis’)

# Update color axis
fig.update_coloraxes(colorbar_title=’Colorbar Title’)

fig.show()
“`

Plotly provides colorbar functionality through the color axis properties.

Matplotlib Color Bar Examples

Let’s see some examples of adding color bars to different matplotlib plot types:

Color Bar for Heatmap

“`python
import numpy as np
import matplotlib.pyplot as plt

data = np.random.random((10,10))

fig, ax = plt.subplots()
im = ax.imshow(data, cmap=’Wistia’)

cbar = fig.colorbar(im, ax=ax)
cbar.set_label(‘Brightness’)

plt.show()
“`

This maps the random data to colors using Wistia colormap and adds a colorbar representing brightness.

Color Bar for Contour Plot

“`python
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-3, 3, 500)
y = np.linspace(-3, 3, 500)
X, Y = np.meshgrid(x, y)
Z = np.exp(-X**2 – Y**2)

fig, ax = plt.subplots()
cp = ax.contour(X, Y, Z, levels=np.logspace(-2, 0, 10))
fig.colorbar(cp, ax=ax, label=’Height’)

plt.show()
“`

This generates a contour plot for the 3D surface exp(-x^2 – y^2) and adds a colorbar showing the height levels for the contour lines.

Color Bar for Pcolormesh

“`python
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 5, 500)
y = np.linspace(0, 5, 500)
X, Y = np.meshgrid(x, y)
Z = np.cos(X**2 + Y**2