Last chance! 50% off DataCamp Premium
Sale ends in
Datavisualisatie is een van de beste manieren (zo niet de beste manier) voor data-analisten en data scientists om complexe informatie weer te geven en betekenisvolle inzichten te genereren. Om het meeste uit je kans te halen om met stakeholders te communiceren, heb ik handige informatie over Matplotlib-kleurenkaarten verzameld.
Zoals je in dit artikel zult zien, is Matplotlib een uiterst veelzijdige en uitbreidbare visualisatiebibliotheek in Python. Het biedt alles, van eenvoudige grafieken tot volledig interactieve visuals. Als je niet bekend bent met Python, raad ik je aan om je eerst in te schrijven voor onze cursus Introduction to Python om de basis te begrijpen. Zelf houd ik ook de Python Cheat Sheet graag bij de hand, omdat die een handig naslagwerk is voor veelgebruikte functies.
Een van de eerste dingen om te bepalen is de keuze tussen sequentiële, divergerende of categorische kleurenkaarten. Andere belangrijke factoren bij het kiezen van kleurenkaarten zijn perceptuele uniformiteit (zodat gelijke verschillen in datapunten als gelijke kleurverschillen worden waargenomen) en het gebruik van kleurenkaarten die geschikt zijn voor kleurenblindheid, zodat je visuals voor iedereen toegankelijk zijn.
Houd ook rekening met standaarden binnen je domein bij het kiezen van kleurenkaarten. In oceanografische studies vertegenwoordigen bijvoorbeeld verschillende blauwtinten verschillende waterdieptes. Als je niet zeker weet welke kleurenkaart geschikt is voor je visualisatie, zijn er verschillende tools en bronnen die je kunnen helpen. Onze eigen cursus Introduction to Data Visualization with Matplotlib helpt je bijvoorbeeld door veel scenario’s heen.
In Python biedt de module matplotlib.colormaps toegang tot ingebouwde kleurenkaarten, wat je helpt om het beste schema voor je project te kiezen. De volgende categorieën komen het meest voor:
Sequentiële kleurenkaarten representeren geordende data die oploopt van lage naar hoge waarden. Ze lopen over van lichte naar donkere tinten en tonen zo de datagrootte op verschillende niveaus. Een voorbeeld van een sequentiële kleurenkaart is een heatmap voor temperatuurdata, waarbij lichtere kleuren koelere temperaturen aangeven en donkere tinten warmere temperaturen.
Stel dat je een dataset hebt met datum- en temperatuurkolommen. Met de onderstaande code maak je een heatmap voor de temperatuur.
# Import required libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
# Step 1: Extract month and day information from the date column
calendar_data = temperature_data.copy() # Create a copy to work with
calendar_data['Month'] = calendar_data['Date'].dt.strftime('%B')
calendar_data['Day'] = calendar_data['Date'].dt.day
# Step 2: Define the order of months for a natural calendar sequence
month_names = ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December']
# Convert the 'Month' column to a categorical type with the specified order
calendar_data['Month'] = pd.Categorical(calendar_data['Month'], categories=month_names, ordered=True)
# Step 3: Pivot the data to create a structured table for the heatmap
monthly_temperature_table = calendar_data.pivot(index='Month', columns='Day', values='Temperature')
# Step 4: Set up the plot for the heatmap
plt.figure(figsize=(12, 8))
# Define a custom normalization for temperature range (optional)
norm = mcolors.Normalize(vmin=15, vmax=35)
# Create the heatmap with a sequential colormap
heatmap = plt.imshow(monthly_temperature_table, cmap='YlOrRd', aspect='auto', norm=norm)
# Add color bar to represent temperature
colorbar = plt.colorbar(heatmap, orientation='horizontal')
colorbar.set_label('Temperature (°C)', labelpad=10)
# Label the axes
plt.xlabel('Day of the Month')
plt.ylabel('Month')
# Set y-ticks to display month names instead of numbers
plt.yticks(ticks=np.arange(len(month_names)), labels=month_names)
# Add a title to the heatmap
plt.title('Monthly Temperature Heatmap (Sequential Colormap)')
# Display the plot
plt.grid(False)
plt.show()

Voorbeeldvisualisatie van sequentiële Matplotlib-kleurenkaarten. Afbeelding door de auteur
Divergerende kleurenkaarten benadrukken data met afwijkingen van een centrale waarde in beide richtingen. Ze gebruiken contrasterende kleuren voor de positieve en negatieve richting. Een veelvoorkomende toepassing is financiële data om winst en verlies weer te geven.
# Set 'Month' as the index
profit_loss_df.set_index('Month', inplace=True)
# Set the figure size
plt.figure(figsize=(8, 4))
# Create a diverging colormap
cmap = plt.cm.RdYlGn
# Display the data as a heatmap using imshow
im = plt.imshow(profit_loss_df.T, cmap=cmap, aspect='auto', vmin=-np.max(np.abs(profit_loss_data)), vmax=np.max(np.abs(profit_loss_data)))
# Add color bar with label
cbar = plt.colorbar(im)
cbar.set_label('Profit/Loss ($)')
# Add annotations to each cell
for i, month in enumerate(profit_loss_df.index):
plt.text(i, 0, f'{profit_loss_df.loc[month, "Profit/Loss"]:.2f}', ha='center', va='center', color='black')
# Set x-axis and y-axis labels and ticks
plt.xlabel('Month')
plt.ylabel('') # No label needed for y-axis
plt.xticks(ticks=range(len(profit_loss_df.index)), labels=profit_loss_df.index, rotation=45)
plt.yticks([]) # Hide y-axis ticks as we only have one row
# Add title
plt.title('Profit/Loss Heatmap (Diverging Colormap)')
# Adjust layout for better display
plt.tight_layout()
# Show plot
plt.show()

Voorbeeldvisualisatie van een divergerende Matplotlib-kleurenkaart. Afbeelding door de auteur.
Cyclische kleurenkaarten zijn handig om data met een herhalend of cyclisch patroon te visualiseren, zoals hoeken, golf-fasen of tijdstippen op een dag. Een voorbeeld is het visualiseren van de fasen van een periodieke functie, zoals een sinusgolf.
# Create data for a sine wave
x = np.linspace(0, 2 * np.pi, 100) # X values from 0 to 2π (one complete cycle)
y = np.sin(x) # Y values (sine of X)
# Create a figure and axis
plt.figure(figsize=(10, 6))
# Create a scatter plot with a cyclic colormap
# Color points by their position in the sine wave cycle
points = plt.scatter(x, y, c=x, cmap='twilight', edgecolor='black')
# Add a color bar to show the phase of the wave
cbar = plt.colorbar(points)
cbar.set_label('Wave Phase (Radians)', rotation=270, labelpad=15)
# Label the axes
plt.xlabel('Angle (Radians)')
plt.ylabel('Sine Value')
# Add a title
plt.title('Sine Wave with Cyclic Colormap (Twilight)')
# Display the plot
plt.grid(True)
plt.show()

Voorbeeldvisualisatie van een cyclische Matplotlib-kleurenkaart. Afbeelding door de auteur.
Kwalitatieve kleurenkaarten zijn ideaal voor categorische data zonder een specifieke volgorde van categorieën. Een veelvoorkomend gebruik is een cirkeldiagram waarin elk segment een andere categorie vertegenwoordigt die gemakkelijk te onderscheiden is.
# Sample categorical data
categories = ['Category A', 'Category B', 'Category C', 'Category D', 'Category E']
values = [20, 35, 25, 10, 10]
# Set the figure size
plt.figure(figsize=(8, 8))
# Define a qualitative colormap manually
colors = ['#8dd3c7', '#ffffb3', '#bebada', '#fb8072', '#80b1d3'] # Manually selected color hex codes
# Create a pie chart
plt.pie(values, labels=categories, autopct='%1.1f%%', startangle=90, colors=colors)
# Equal aspect ratio ensures the pie is drawn as a circle
plt.axis('equal')
# Add a title
plt.title('Pie Chart with Qualitative Colormap')
# Display the chart
plt.show()

Voorbeeldvisualisatie van een kwalitatieve Matplotlib-kleurenkaart. Afbeelding door de auteur.
Regenboogkleurenkaarten zoals hsv worden gebruikt wanneer een breed scala aan tinten nodig is.
# Generate cyclic data
x = np.linspace(0, 2 * np.pi, 500)
y = np.sin(x)
# Create a plot with rainbow colormap
plt.scatter(x, y, c=x, cmap='hsv', s=50)
# Add a color bar
plt.colorbar(label='Phase')
# Add labels and title
plt.xlabel('Angle (radians)')
plt.ylabel('Sine Value')
plt.title('Cyclic Data Visualization using HSV Colormap')
# Display the plot
plt.show()

Voorbeeldvisualisatie van een regenboogkleurige Matplotlib-kleurenkaart. Afbeelding door de auteur.
Kleurenkaarten zoals inferno en plasma bieden betere zichtbaarheid op verschillende weergavemedia.
# Generate synthetic elevation data
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2)) * 100 # Elevation data
# Plot the elevation data using the 'plasma' colormap
plt.contourf(X, Y, Z, cmap='plasma')
# Add a color bar
plt.colorbar(label='Elevation (m)')
# Add title and labels
plt.title('Topographic Map (Plasma Colormap)')
plt.xlabel('X Coordinate')
plt.ylabel('Y Coordinate')
# Display the plot
plt.show()

Voorbeeldvisualisatie van een perceptueel uniforme Matplotlib-kleurenkaart. Afbeelding door de auteur.
Hoewel Matplotlib een grote verscheidenheid aan ingebouwde kleurenkaarten heeft, zijn er situaties waarin je je kleuren wilt aanpassen. De belangrijkste tools om aangepaste kleurenkaarten in Matplotlib te maken zijn ListedColormap en LinearSegmentedColormap.
ListedColomap laat je een kleurenkaart maken op basis van een lijst met specifieke kleuren. Deze methode is handig wanneer je specifieke kleuren wilt toewijzen aan afzonderlijke categorieën in categorische data.
from matplotlib.colors import ListedColormap
# Categorical data
categories = ['Category A', 'Category B', 'Category C', 'Category D']
values = [25, 40, 35, 30]
# Custom color list for the colormap (e.g., shades of blue, green, red, and purple)
custom_colors = ['#1f77b4', '#2ca02c', '#d62728', '#9467bd']
# Create a ListedColormap using the custom colors
custom_cmap = ListedColormap(custom_colors)
# Set the figure size
plt.figure(figsize=(8, 6))
# Create a bar plot with the custom colormap
bars = plt.bar(categories, values, color=custom_cmap.colors)
# Add a title
plt.title('Bar Chart with Custom ListedColormap')
# Label the axes
plt.xlabel('Categories')
plt.ylabel('Values')
# Display the plot
plt.show()

Aangepaste Matplotlib-kleurenkaart met ListedColormap. Afbeelding door de auteur.
LinearSegmentedColormap laat je kleurenkaarten maken die vloeiend tussen kleuren overlopen. Dit is handig omdat continue data vaak graduele kleurveranderingen vereist. Hier geef ik ook het aantal intervallen op dat ik in mijn visual wil.
from matplotlib.colors import LinearSegmentedColormap
# Create a grid of values for a 2D Gaussian function
x = np.linspace(-2, 2, 500)
y = np.linspace(-2, 2, 500)
X, Y = np.meshgrid(x, y)
Z = np.exp(- (X**2 + Y**2))
# Define a custom colormap that transitions from blue to white to red
colors = ['blue', 'white', 'red']
custom_cmap = LinearSegmentedColormap.from_list('blue_white_red', colors)
# Adjust the number of color classes (discrete levels)
# Specify the number of levels (e.g., 10 for 10 distinct color bands)
num_classes = 10
levels = np.linspace(Z.min(), Z.max(), num_classes)
# Set the figure size
plt.figure(figsize=(8, 6))
# Plot the 2D Gaussian function with the adjusted colormap
contour = plt.contourf(X, Y, Z, levels=levels, cmap=custom_cmap)
# Add a color bar to show the discrete color classes
plt.colorbar(contour, label='Gaussian Function Value')
# Add labels for the axes
plt.xlabel('X')
plt.ylabel('Y')
# Add a title
plt.title(f'2D Gaussian with {num_classes} Discrete Color Classes')
# Display the plot
plt.show()

Matplotlib, het aantal kleurklassen aanpassen. Afbeelding door de auteur.
Je kunt de intensiteit of het bereik van kleuren in een bestaande kleurenkaart sturen door de normalisatie te manipuleren of door een subset van de beschikbare kleuren te gebruiken. In het volgende voorbeeld worden de kleurbereiken bijgesneden om temperaturen tussen 16 en 40 graden Celsius te tonen.
# Set up the plot for the heatmap
plt.figure(figsize=(12, 8))
# Define a custom normalization for temperature range
norm = mcolors.Normalize(vmin=16, vmax=40)
# Create the heatmap with a sequential colormap
heatmap = plt.imshow(monthly_temperature_table, cmap='YlOrRd', aspect='auto', norm=norm)
# Add color bar to represent temperature
colorbar = plt.colorbar(heatmap, orientation='horizontal')
colorbar.set_label('Temperature (°C)', labelpad=10)
# Label the axes
plt.xlabel('Day of the Month')
plt.ylabel('Month')
# Set y-ticks to display month names instead of numbers
plt.yticks(ticks=np.arange(len(month_names)), labels=month_names)
# Add a title to the heatmap
plt.title('Monthly Temperature Heatmap (Sequential Colormap)')
# Display the plot
plt.grid(False)
plt.show()

Matplotlib kleurbereiken en intensiteit aanpassen. Afbeelding door de auteur.
Je kunt ook bestaande kleurenkaarten combineren door meerdere kaarten te mengen om complexere visualisaties te maken.
from matplotlib.colors import LinearSegmentedColormap, Normalize
# Create synthetic elevation data
x = np.linspace(-180, 180, 500) # Longitude
y = np.linspace(-90, 90, 250) # Latitude
X, Y = np.meshgrid(x, y)
Z = 5000 * np.sin(np.sqrt(X**2 + Y**2) * np.pi / 180) # Synthetic elevation data
# Define the base colormaps ('viridis' and 'cividis')
cmap1 = plt.get_cmap('viridis')
cmap2 = plt.get_cmap('cividis')
# Create a custom colormap by blending the two base colormaps
def blend_colormaps(cmap1, cmap2, blend_ratio=0.5):
"""Blend two colormaps together."""
c1 = cmap1(np.linspace(0, 1, 256))
c2 = cmap2(np.linspace(0, 1, 256))
blended_colors = (1 - blend_ratio) * c1 + blend_ratio * c2
return LinearSegmentedColormap.from_list('blended_cmap', blended_colors)
# Create the blended colormap
custom_cmap = blend_colormaps(cmap1, cmap2, blend_ratio=0.5)
# Normalize the data for visualization
norm = Normalize(vmin=-5000, vmax=5000)
# Set the figure size
plt.figure(figsize=(12, 6))
# Plot the synthetic elevation data with the blended colormap
contour = plt.contourf(X, Y, Z, levels=100, cmap=custom_cmap, norm=norm)
# Add a color bar to show the blended color mapping
plt.colorbar(contour, label='Elevation (meters)')
# Add labels for the axes
plt.xlabel('Longitude')
plt.ylabel('Latitude')
# Add a title
plt.title('Geographical Elevation Data with Blended Colormap (Viridis + Cividis)')
# Display the plot
plt.show()

Matplotlib bestaande kleurenkaarten combineren. Afbeelding door de auteur.
Je kunt elke kleurenkaart in Matplotlib omkeren door de suffix _r aan de naam toe te voegen.
# Set up the plot for the heatmap
plt.figure(figsize=(12, 8))
# Create a custom normalization for the color range
norm = mcolors.Normalize(vmin=16, vmax=40)
# Plot the heatmap using imshow with the sequential colormap
im = plt.imshow(monthly_temperature_table, cmap='YlOrRd_r', norm=norm, aspect='equal')
# Add a color bar with a horizontal orientation
cbar = plt.colorbar(im, orientation='horizontal', pad=0.1)
cbar.set_label('Temperature (°C)', labelpad=10)
# Add labels for the axes
plt.xlabel('Day of the Month')
plt.ylabel('Month')
# Set y-ticks to display month names instead of numbers
plt.yticks(ticks=np.arange(len(month_names)), labels=month_names)
# Add a title
plt.title('Temperature Heatmap (Sequential Colormap)')
# Display the plot
plt.show()

Matplotlib kleurenkaarten omkeren met de suffix _r. Afbeelding door de auteur.
Bij het werken met kleurenkaarten in Matplotlib kun je fouten tegenkomen die je workflow beïnvloeden. Hieronder staan enkele fouten en hoe je ze kunt oplossen.
Deze fout treedt op wanneer je Matplotlib-versies vóór 3.4.0 gebruikt om toegang te krijgen tot matplotlib.colormaps. De colormaps-attribuut is geïntroduceerd in Matplotlib 3.4.0. Controleer eerst je Matplotlib-versie met de onderstaande code om dit probleem te troubleshooten.
import matplotlib
print(matplotlib.__version__)
Upgrade met het volgende pip-commando.
pip install --upgrade matplotlib
Als je problemen ondervindt bij het upgraden van je Matplotlib-versie, probeer dan de volgende methode om kleurenkaarten te benaderen.
plt.get_cmap('viridis') # instead of matplotlib.colormaps['viridis']
Je kunt onjuiste kleurtoewijzingen ervaren wanneer je een waarde buiten het verwachte bereik doorgeeft of wanneer de kleurenkaart verkeerd wordt toegepast. Onjuiste toewijzing kan ook ontstaan als een kleurenkaart bedoeld is voor continue data maar wordt toegepast op categorische data, of andersom.
Zorg ervoor dat je data binnen het verwachte bereik valt: normaliseer of schaal die altijd met de parameters vmax en vmin.
import matplotlib.colors as mcolors
# Create a sample temperature dataset
data = np.random.rand(10, 10) * 100 # Adjust the range to match your data
# Create a color normalization instance to scale the data to the colormap's range
norm = mcolors.Normalize(vmin=0, vmax=100)
# Create a heatmap using the 'viridis' colormap and the specified normalization
plt.imshow(data, cmap='viridis', norm=norm, interpolation='nearest')
plt.colorbar()
plt.show()
Voor meer controle kun je de kleurgrenzen expliciet definiëren met de parameters boundaries of norm in de plotfuncties.
Bij het werken met discrete of laag-resolutie data kun je ongewenste kleurbanden, overdreven contrast of kleurdoorloop zien. Dit gebeurt wanneer je data een beperkt bereik heeft maar wordt weergegeven met een continue kleurenkaart.
Los dit op door meer datapunten te gebruiken of het aantal kleurlevels aan te passen om overgangen te verzachten.
# Increase the number of bins in the colormap
cmap = plt.get_cmap('viridis', 256)
plt.imshow(data, cmap=cmap)
Je kunt de kleurenkaart ook opsplitsen in vaste levels om discrete data waar nodig te verwerken.
cmap = plt.get_cmap('inferno', 10) # Divide colormap into 10 discrete levels
plt.imshow(data, cmap=cmap)
Controleer ook de weergave-instellingen en pas de resolutie aan, zeker bij het opslaan van visualisaties, om grafieken met lage resolutie te voorkomen
plt.savefig('plot.png', dpi=300) # Save the figure with a higher resolution
Kleurvervorming treedt op wanneer data extreme waarden bevat buiten het verwachte kleurbereik. Daardoor worden delen van de data geclipt en krijgen ze de minimale of maximale kleur van de kleurenkaart.
Voorkom kleurvervorming door de kleurlimieten met vmin en vmax af te stemmen op het bereik van je data, zodat clipping uitblijft.
plt.imshow(data, cmap='plasma', vmin=0, vmax=100)
Gebruik ook robuuste schaling om outliers te behandelen door aangepaste limieten te zetten die extreme waarden uitsluiten.
import numpy as np
robust_vmin, robust_vmax = np.percentile(data, [2, 98]) # Use percentiles to remove extreme outliers
plt.imshow(data, cmap='inferno', vmin=robust_vmin, vmax=robust_vmax)
Als er een probleem is met hoe data in het 3D-oppervlak wordt gemapt, kunnen kleurenkaarten in 3D-visualisaties onjuist verschijnen. Zorg ervoor dat de z-asdata is genormaliseerd zodat die binnen het verwachte bereik van de kleurenkaart valt. Gebruik ook passende kleurlimieten om het volledige bereik van de z-waarden te vangen.
from mpl_toolkits.mplot3d import Axes3D
# Generate sample data for a 3D surface plot
X, Y = np.meshgrid(np.linspace(-5, 5, 50), np.linspace(-5, 5, 50))
Z = np.sin(np.sqrt(X**2 + Y**2))
# Create a 3D axes object
ax = plt.axes(projection='3d')
# Plot the surface using the 'viridis' colormap and adjusting the color limits
ax.plot_surface(X, Y, Z, cmap='viridis', vmin=np.min(Z), vmax=np.max(Z))
plt.show()
De juiste kleurenkaart kiezen is een belangrijke stap, omdat die echt bepaalt hoe gebruikers je data bekijken en begrijpen. Naar mijn mening is het een grote fout om veel tijd te besteden aan data-analyse en vervolgens slordig te zijn in de laatste stap: het communiceren van je bevindingen.
Gelukkig biedt Matplotlib veel opties om ervoor te zorgen dat je visuals een overtuigend verhaal vertellen. Schrijf je in voor onze cursus, Introduction to Data Visualization with Matplotlib, om een expert te worden. En als je als Python-gebruiker ook Seaborn inzet voor visualisatie (handig om beide te kennen), lees dan onze Snelle gids voor het kiezen van kleuren in Seaborn en volg die op met onze cursus Introduction to Data Visualization with Seaborn.
De standaardkleurenkaart in Matplotlib is viridis.
Om de fout AttributeError: module 'matplotlib' has no attribute 'colormaps' op te lossen, upgrade je je Matplotlib-bibliotheek naar een versie hoger dan 3.4.0.
Je kunt de toegankelijkheid van kleurenkaarten voor kleurenblinde gebruikers testen met tools zoals Coblis (Color Blindness Simulator) of externe libraries zoals palettable om te simuleren hoe kleurenkaarten eruitzien voor kleurenblinde kijkers.
Een perceptueel uniforme kleurenkaart zorgt ervoor dat gelijke stappen in de data leiden tot gelijke waarneembare kleurveranderingen, waardoor interpretatie van de visualisatie accurater wordt.
Ja, externe libraries zoals palettable of cmocean bieden aangepaste kleurenkaarten die je kunt integreren met Matplotlib voor gespecialiseerde visualisatiebehoeften.
Leer Python en datavisualisatie met DataCamp
Cursus
Cursus
Cursus

blog
Adel Nehme
15 min