Colormaps in Matplotlib
Color maps assign colors to numerical values, allowing us to visualize data with different shades or hues. They provide a visual representation of the data’s magnitude or intensity, making it easier to interpret trends, patterns, and variations.
Imagine you have a dataset showcasing temperature variations across a map. A colormap helps represent different temperatures using a range of colors—say, blue for cold and red for hot. This way, you not only see the temperatures but also feel the heat map come alive!
Exploring Different Types of Colormaps
There are 3 types of color maps, each suited for different types of data and visualization purposes.
Sequential Colormaps | Diverging Colormaps | Qualitative Colormaps |
---|---|---|
Sequential colormaps smoothly transition from one color to another, typically from light to dark or from low to high values in your data. Think of a temperature map where colors smoothly shift from cool to warm tones. | Diverging color maps use two contrasting colors to highlight deviations from a central value, ideal for showing positive and negative deviations from a mean or midpoint. | Qualitative color maps are designed for categorical data and use distinct colors without any inherent ordering. |
Using Colormaps for Scatter Plots
Scatter plots benefit from colormaps by assigning different colors to data points based on additional information, enabling the visualization of multidimensional data.
Example:
# Applying a colormap to a scatter plot import numpy as np x = np.random.rand(100) y = np.random.rand(100) colors = np.random.rand(100) # Defining colors based on data range plt.scatter(x, y, c=colors, cmap='plasma') plt.colorbar() plt.title('Scatter Plot with Colormap') plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.show()
Output:
For Bar Plots
In bar plots, colormaps can be utilized to color bars differently based on categories or values, making comparisons more intuitive.
There are two methods for Bar Plots.
Example: Using plt.get_cmap
In this example, each category gets a distinct color from the 'tab10'
colormap, making it easy to differentiate between categories.
import matplotlib.pyplot as plt # Example data product_categories = ['Category A', 'Category B', 'Category C', 'Category D'] sales_data = [30, 15, 40, 25] # Grabbing colors from 'tab10' colormap colors = plt.get_cmap('tab10').colors # Coloring bars with distinct colors for each category plt.bar(product_categories, sales_data, color=colors) plt.title('Bar Plot with Different Colors (tab10 Colormap)') plt.xlabel('Categories') plt.ylabel('Sales') plt.show()
Output:
This method fetches ten different colors from the 'tab10'
palette. Great for making each category in the plot stand out with its unique color.
Example: Using plt.cm.viridis
In this example, the 'viridis'
colormap is used to generate a smooth transition of colors across the categories in the bar plot.
import matplotlib.pyplot as plt import numpy as np # Example data categories = ['Category 1', 'Category 2', 'Category 3', 'Category 4'] values = [15, 30, 45, 60] # Getting a smooth color blend from 'viridis' colormap colors = plt.cm.viridis(np.linspace(0, 1, len(categories))) # Coloring bars with a smooth color transition plt.bar(categories, values, color=colors) plt.title('Bar Plot with Smooth Colors (viridis Colormap)') plt.xlabel('Categories') plt.ylabel('Values') plt.show()
Output:
For Heatmaps
Colormaps are a perfect fit for heatmaps, where different colors represent varying intensities or values across a grid.
Example:
# Applying a colormap to a heatmap data = np.random.rand(10, 10) plt.imshow(data, cmap='coolwarm') plt.colorbar() plt.title('Heatmap with Colormap') plt.show()
Output:
Real-World Example: Visualizing Student Performance Over Semesters
Imagine you’re an educator analyzing the academic performance of students across multiple semesters. You want to create visualizations that capture the progression of their grades over time. Here we will use sequential colormaps.
So, you have a dataset containing students’ performance scores across five semesters. Each student’s grades in different subjects are recorded, and you want to visualize their overall performance using a sequential colormap.
# Sample data (simulated student performance across semesters) num_students = 50 num_semesters = 5 grades = np.random.randint(60, 100, size=(num_students, num_semesters))
Let’s use the 'viridis_r'
colormap to represent students’ overall performance across semesters. In this colormap, colors progress from lighter to darker, making it ideal for showcasing continuous progression.
Example:
import matplotlib.pyplot as plt import numpy as np # Sample data (simulated student performance across semesters) num_students = 50 num_semesters = 5 grades = np.random.randint(60, 100, size=(num_students, num_semesters)) # Calculate average performance across semesters for each student average_grades = np.mean(grades, axis=1) # Plotting student performance using 'viridis_r' colormap plt.figure(figsize=(8, 6)) plt.scatter(range(num_students), average_grades, c=average_grades, cmap='viridis_r', alpha=0.8) # Using 'viridis_r' for reverse scale plt.colorbar(label='Average Grade') plt.title('Student Performance Over Semesters') plt.xlabel('Students') plt.ylabel('Average Grade') plt.show()
Output:
In this visualization, each dot represents a student, and its color represents their average grade using the 'viridis_r'
colormap which is the reverse version of 'viridis'
Lighter colors indicate lower average grades, progressing toward darker shades for higher grades. You can easily spot trends—students with consistent improvement display a transition from lighter to darker colors across semesters.
Real-World Example: Visualizing Sentiment Analysis Across Regions
Imagine you’re analyzing sentiment data collected from different regions regarding a new product launch. You want to create visualizations that highlight variations in sentiment (positive and negative) across regions. Diverging colormaps will help us effectively display this data!
So, you have a dataset containing sentiment scores for five regions across multiple product categories. The sentiment scores range from -1 (negative sentiment) to 1 (positive sentiment). You aim to visualize these sentiment scores using a diverging colormap.
# Sample data (simulated sentiment scores across regions) num_regions = 5 num_categories = 4 sentiment_scores = np.random.uniform(-1, 1, size=(num_regions, num_categories))
Let’s employ the 'RdBu'
colormap to represent sentiment scores across regions. This colormap uses red for negative sentiment, blue for positive sentiment, and white for neutral sentiment around a midpoint.
import matplotlib.pyplot as plt import numpy as np # Sample data (simulated sentiment scores across regions) num_regions = 5 num_categories = 4 sentiment_scores = np.random.uniform(-1, 1, size=(num_regions, num_categories)) # Plotting sentiment scores using 'RdBu' colormap plt.figure(figsize=(8, 6)) plt.imshow(sentiment_scores, cmap='RdBu', aspect='auto') plt.colorbar(label='Sentiment Score') plt.title('Sentiment Analysis Across Regions') plt.xlabel('Categories') plt.ylabel('Regions') plt.xticks(np.arange(num_categories), labels=[f'Category {i+1}' for i in range(num_categories)]) plt.yticks(np.arange(num_regions), labels=[f'Region {i+1}' for i in range(num_regions)]) plt.show()
Output:
In this visualization, each cell represents sentiment scores for a specific region and product category using the 'RdBu'
colormap. Shades of red indicate negative sentiment, blue represents positive sentiment, and white depicts neutral sentiment. The midpoint (white) signifies a balanced sentiment.
Real-World Example: Visualizing Product Categories in a Sales Report
Imagine you’re a sales analyst examining the performance of various product categories in a retail business. You want to create visualizations that distinguish different product categories effectively. Here’s where qualitative colormaps come into play!
Let’s say, you have a sales dataset with information on different product categories sold by a retail company. Each category has unique attributes, and you aim to visualize their sales performances using a qualitative colormap.
# Sample data (simulated sales performance for different product categories) product_categories = ['Electronics', 'Clothing', 'Books', 'Home Decor', 'Sports', 'Beauty', 'Toys', 'Food', 'Accessories', 'Stationery'] sales_data = np.random.randint(1000, 5000, size=len(product_categories))
For this, we will use 'tab10'
qualitative colormap to represent different product categories in your sales report. This colormap provides a set of ten distinct and easily distinguishable colors, perfect for categorizing various product types.
Example:
import matplotlib.pyplot as plt import numpy as np # Sample data (simulated sales performance for different product categories) product_categories = ['Electronics', 'Clothing', 'Books', 'Home Decor', 'Sports', 'Beauty', 'Toys', 'Food', 'Accessories', 'Stationery'] sales_data = np.random.randint(1000, 5000, size=len(product_categories)) # Plotting sales performance using the 'tab10' colormap plt.figure(figsize=(8, 6)) plt.bar(product_categories, sales_data, color=plt.get_cmap('tab10').colors) plt.title('Sales Performance by Product Category') plt.xlabel('Product Categories') plt.ylabel('Sales Amount ($)') plt.xticks(rotation=45, ha='right') plt.tight_layout() plt.show()
Output:
Popular Colormaps Categorized By Their Types
This table lists popular colormaps in each category available in Matplotlib. These colormaps offer a wide range of choices for visualizing different types of data effectively.
Sequential Colormaps | Diverging Colormaps | Qualitative Colormaps |
---|---|---|
‘viridis’ | ‘coolwarm’ | ‘tab10’ |
‘plasma’ | ‘RdBu’ | ‘tab20’ |
‘inferno’ | ‘bwr’ | ‘tab20b’ |
‘magma’ | ‘seismic’ | ‘tab20c’ |
‘cividis’ | ‘Pastel1’ | |
‘spring’ | ‘Pastel2’ | |
‘summer’ | ‘Paired’ | |
‘autumn’ | ‘Set1’ | |
‘winter’ | ‘Set2’ | |
‘cool’ | ‘Set3’ |