Chuyển đến nội dung chính

Matplotlib Colormaps: Tùy chỉnh bảng màu của bạn

Nâng tầm trực quan hóa với Matplotlib colormap. Học cách chọn colormap phù hợp, điều chỉnh lớp màu và khắc phục sự cố trực quan hóa thường gặp.
· 6 phút đọc

Khám phá cùng AI

Trực quan hóa dữ liệu là một trong những cách tốt nhất (nếu không muốn nói là tốt nhất) để nhà phân tích dữ liệu và nhà khoa học dữ liệu biểu diễn thông tin phức tạp và tạo ra những insight hữu ích. Để bạn tận dụng tối đa cơ hội giao tiếp với các bên liên quan, tôi đã tổng hợp những thông tin hữu ích về colormap trong Matplotlib. 

Như bạn sẽ thấy trong bài viết này, Matplotlib là một thư viện trực quan hóa cực kỳ linh hoạt và có thể mở rộng trong Python. Nó cung cấp mọi lựa chọn, từ biểu đồ đơn giản đến hình ảnh tương tác hoàn chỉnh. Nếu bạn chưa quen với Python, tôi khuyến khích bạn đăng ký khóa học Introduction to Python của chúng tôi trước khi bắt đầu để nắm vững nền tảng. Cá nhân tôi cũng luôn giữ Python Cheat Sheet bên cạnh vì đây là tài liệu tham khảo hữu ích cho các hàm thông dụng.

Chọn Matplotlib Colormap phù hợp

Một trong những điều đầu tiên cần cân nhắc là quyết định giữa colormap tuần tự (sequential), phân kỳ (diverging) hoặc định tính (categorical). Các yếu tố quan trọng khác khi chọn colormap gồm tính đồng nhất về cảm nhận (perceptual uniformity), nghĩa là các khác biệt bằng nhau trong giá trị dữ liệu được cảm nhận là khác biệt bằng nhau về màu sắc, và sử dụng các tùy chọn colormap thân thiện với người mù màu để biểu đồ của bạn dễ tiếp cận với mọi đối tượng.

Bạn cũng nên cân nhắc các chuẩn trong từng lĩnh vực khi chọn colormap. Ví dụ, các sắc độ xanh khác nhau biểu thị độ sâu nước khác nhau trong các nghiên cứu hải dương học. Nếu bạn chưa chắc về colormap phù hợp cho hình minh họa của mình, có nhiều công cụ và tài nguyên để tham khảo. Đặc biệt, khóa học Introduction to Data Visualization with Matplotlib của chúng tôi sẽ giúp bạn xử lý nhiều kịch bản khác nhau.

Các loại colormap trong Matplotlib

Trong Python, mô-đun matplotlib.colormaps cung cấp quyền truy cập vào các colormap tích hợp sẵn, giúp bạn chọn lược đồ màu phù hợp nhất cho dự án. Sau đây là các nhóm tùy chọn phổ biến nhất:

Colormap tuần tự (Sequential)

Colormap tuần tự biểu diễn dữ liệu có thứ tự tăng dần từ giá trị thấp đến cao. Chúng chuyển từ tông sáng sang tối, thể hiện độ lớn của dữ liệu ở các mức khác nhau. Ví dụ điển hình là heatmap cho dữ liệu nhiệt độ, nơi màu sáng biểu thị nhiệt độ thấp hơn và tông đậm biểu thị nhiệt độ cao hơn.

Giả sử bạn có một tập dữ liệu với các cột ngày và nhiệt độ. Đoạn mã sau sẽ tạo heatmap cho nhiệt độ.

# 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()

Ví dụ trực quan hóa colormap tuần tự của Matplotlib.

Ví dụ trực quan hóa colormap tuần tự của Matplotlib. Ảnh: Tác giả

Colormap phân kỳ (Diverging)

Colormap phân kỳ làm nổi bật dữ liệu có độ lệch so với một giá trị trung tâm theo cả hai hướng. Chúng dùng các màu tương phản cho hướng dương và âm. Ứng dụng phổ biến là dữ liệu tài chính để biểu diễn lãi và lỗ.

# 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()

Ví dụ trực quan hóa colormap phân kỳ của Matplotlib.

Ví dụ trực quan hóa colormap phân kỳ của Matplotlib. Ảnh: Tác giả.

Colormap chu kỳ (Cyclic)

Colormap chu kỳ hữu ích để trực quan hóa dữ liệu mang tính lặp lại hoặc tuần hoàn, như góc, pha sóng, hoặc thời gian trong ngày. Ví dụ là trực quan hóa các pha của một hàm tuần hoàn như sóng sin.

# 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()

Ví dụ trực quan hóa colormap chu kỳ của Matplotlib.

Ví dụ trực quan hóa colormap chu kỳ của Matplotlib. Ảnh: Tác giả.

Colormap định tính (Qualitative)

Colormap định tính rất phù hợp để biểu diễn dữ liệu phân loại không có trật tự. Trường hợp sử dụng phổ biến là biểu đồ tròn, nơi mỗi lát biểu thị một hạng mục khác nhau và dễ phân biệt.

# 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()

Ví dụ trực quan hóa colormap định tính của Matplotlib

Ví dụ trực quan hóa colormap định tính của Matplotlib. Ảnh: Tác giả.

Colormap cầu vồng (Rainbow)

Colormap cầu vồng như hsv được dùng khi cần một dải sắc độ rộng.

# 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()

Ví dụ trực quan hóa colormap cầu vồng của Matplotlib.

Ví dụ trực quan hóa colormap cầu vồng của Matplotlib. Ảnh: Tác giả.

Colormap đồng nhất theo cảm nhận

Các colormap như inferno và plasma cho khả năng hiển thị tốt hơn trên nhiều phương tiện hiển thị khác nhau.

# 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()

Ví dụ trực quan hóa colormap đồng nhất theo cảm nhận của Matplotlib.

Ví dụ trực quan hóa colormap đồng nhất theo cảm nhận của Matplotlib. Ảnh: Tác giả.

Tạo và chỉnh sửa Matplotlib Colormap

Dù Matplotlib có rất nhiều colormap tích hợp sẵn, vẫn có những tình huống bạn muốn tùy chỉnh màu sắc. Công cụ chủ đạo để tạo colormap tùy chỉnh trong Matplotlib là ListedColormap và LinearSegmentedColormap.

Tạo colormap tùy chỉnh với ListedColormap

ListedColomap cho phép bạn tạo colormap từ một danh sách màu cụ thể. Cách này hữu ích khi gán màu cố định cho các hạng mục riêng biệt trong dữ liệu phân loại. 

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()

Colormap tùy chỉnh Matplotlib với ListedColormap.

Colormap tùy chỉnh Matplotlib với ListedColormap. Ảnh: Tác giả.

Tạo colormap tùy chỉnh với LinearSegmentedColormap

LinearSegmentedColormap cho phép bạn tạo các colormap chuyển đổi mượt giữa các màu. Điều này đáng biết vì dữ liệu liên tục thường cần thay đổi màu theo dạng gradient. Ở đây, tôi cũng chỉ định số khoảng màu mong muốn cho hình minh họa.

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()

Điều chỉnh số lớp màu tùy chỉnh trong Matplotlib.

Điều chỉnh số lớp màu tùy chỉnh trong Matplotlib. Ảnh: Tác giả.

Tùy chỉnh phạm vi và cường độ màu

Bạn có thể kiểm soát cường độ hoặc phạm vi màu trong một colormap hiện có bằng cách thao tác việc chuẩn hóa (normalization) hoặc cắt lát để dùng một phần con của các màu sẵn có. Trong ví dụ sau, phạm vi màu được cắt để hiển thị nhiệt độ trong khoảng 16 đến 40 độ C.

# 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()

Tùy chỉnh phạm vi và cường độ màu trong Matplotlib.

Tùy chỉnh phạm vi và cường độ màu trong Matplotlib. Ảnh: Tác giả.

Kết hợp các colormap hiện có

Bạn cũng có thể kết hợp các colormap hiện có bằng cách pha trộn nhiều colormap để tạo trực quan hóa phức tạp hơn.

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()

Kết hợp các colormap hiện có trong Matplotlib.

Kết hợp các colormap hiện có trong Matplotlib. Ảnh: Tác giả.

Đảo ngược colormap bằng hậu tố _r

Bạn có thể đảo ngược bất kỳ colormap nào trong Matplotlib bằng cách thêm hậu tố _r vào tên của nó.

# 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()

Đảo ngược colormap trong Matplotlib bằng hậu tố _r

Đảo ngược colormap trong Matplotlib bằng hậu tố _r. Ảnh: Tác giả.

Xử lý các lỗi thường gặp với Matplotlib Colormap

Khi làm việc với colormap trong Matplotlib, bạn có thể gặp các lỗi ảnh hưởng đến quy trình. Dưới đây là một số lỗi và cách khắc phục.

AttributeError: module 'matplotlib' has no attribute 'colormaps’

Lỗi này xảy ra khi bạn dùng Matplotlib phiên bản trước 3.4.0 để truy cập matplotlib.colormaps. Thuộc tính colormaps được giới thiệu trong Matplotlib 3.4.0. Trước tiên, hãy kiểm tra phiên bản Matplotlib của bạn bằng đoạn mã dưới đây để xử lý lỗi này.

import matplotlib
print(matplotlib.__version__)

Nâng cấp bằng lệnh pip sau.

pip install --upgrade matplotlib

Nếu bạn gặp vấn đề khi nâng cấp phiên bản Matplotlib, hãy thử cách sau để truy cập colormap.

plt.get_cmap('viridis')  # instead of matplotlib.colormaps['viridis']

Gán màu không chính xác

Bạn có thể gặp tình trạng gán màu không chính xác khi truyền giá trị nằm ngoài phạm vi mong đợi hoặc khi colormap được áp dụng sai cách. Việc gán màu sai cũng có thể xảy ra nếu colormap dành cho dữ liệu liên tục nhưng lại áp dụng cho dữ liệu phân loại hoặc ngược lại.

Để đảm bảo dữ liệu nằm trong phạm vi mong đợi, hãy luôn chuẩn hóa hoặc co giãn dữ liệu bằng tham số vmax và 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()

Để kiểm soát chi tiết hơn, bạn có thể định nghĩa ranh giới màu rõ ràng bằng tham số boundaries hoặc norm trong các hàm vẽ.

Hiện tượng nhiễu hình và kết quả ngoài ý muốn

Khi làm việc với dữ liệu rời rạc hoặc có độ phân giải thấp, bạn có thể gặp các dải màu không mong muốn, độ tương phản quá mức, hoặc lem màu. Vấn đề xảy ra khi dữ liệu có phạm vi hạn chế nhưng được hiển thị bằng colormap liên tục.

Để khắc phục, hãy dùng nhiều điểm dữ liệu hơn hoặc điều chỉnh số mức màu để làm mượt chuyển tiếp.

# Increase the number of bins in the colormap
cmap = plt.get_cmap('viridis', 256)
plt.imshow(data, cmap=cmap)

Bạn có thể chia colormap thành các mức cố định để xử lý dữ liệu rời rạc khi phù hợp.

cmap = plt.get_cmap('inferno', 10)  # Divide colormap into 10 discrete levels
plt.imshow(data, cmap=cmap)

Bạn cũng có thể kiểm tra cài đặt hiển thị và điều chỉnh độ phân giải, đặc biệt khi lưu hình, để tránh biểu đồ độ phân giải thấp

plt.savefig('plot.png', dpi=300)  # Save the figure with a higher resolution

Biến dạng màu do cắt ngưỡng (clipping)

Biến dạng màu xảy ra khi dữ liệu chứa các giá trị cực đoan nằm ngoài phạm vi màu dự kiến. Điều này khiến một phần dữ liệu bị cắt ngưỡng và gán về màu tối thiểu hoặc tối đa trong colormap.

Để tránh biến dạng màu, hãy điều chỉnh giới hạn màu bằng vmin và vmax để khớp với phạm vi dữ liệu, tránh bị cắt ngưỡng.

plt.imshow(data, cmap='plasma', vmin=0, vmax=100)

Bạn cũng nên dùng phép co giãn “robust” để xử lý ngoại lệ bằng cách đặt giới hạn tùy chỉnh loại trừ các giá trị cực đoan.

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)

Colormap hiển thị không đúng trong biểu đồ 3D

Nếu có vấn đề với cách ánh xạ dữ liệu trên bề mặt 3D, colormap có thể không hiển thị đúng trong biểu đồ 3D. Để khắc phục, hãy đảm bảo dữ liệu trục z được chuẩn hóa để phù hợp phạm vi mong đợi của colormap. Đồng thời dùng giới hạn colormap phù hợp để bao quát đầy đủ dải giá trị z.

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()

Kết luận

Chọn đúng colormap là bước quan trọng vì nó thực sự ảnh hưởng đến cách người dùng nhìn nhận và hiểu dữ liệu của bạn. Theo tôi, dành nhiều thời gian để phân tích dữ liệu nhưng lại cẩu thả ở bước cuối cùng — phần bạn truyền đạt phát hiện — là một sai lầm lớn.

May mắn là Matplotlib cung cấp rất nhiều lựa chọn để đảm bảo hình ảnh của bạn kể được một câu chuyện thuyết phục. Hãy đăng ký khóa học Introduction to Data Visualization with Matplotlib để trở thành chuyên gia. Ngoài ra, nếu bạn là người dùng Python đồng thời dùng Seaborn để trực quan hóa (biết cả hai là rất tốt), hãy đọc Quick Guide to Picking Colors in Seaborn và tiếp tục với khóa học Introduction to Data Visualization with Seaborn.

Allan Ouko

Tác giả

Allan Ouko

Biên tập viên kỹ thuật về Khoa học dữ liệu với kinh nghiệm thực tế trong phân tích dữ liệu, trí tuệ doanh nghiệp và khoa học dữ liệu. Tôi viết nội dung thực tiễn, tập trung vào ngành về SQL, Python, Power BI, Databricks và kỹ thuật dữ liệu, dựa trên công việc phân tích trong thế giới thực. Bài viết của tôi kết nối chiều sâu kỹ thuật với tác động kinh doanh, giúp các chuyên gia chuyển đổi dữ liệu thành những quyết định vững chắc.

Câu hỏi thường gặp về Matplotlib Colormaps

Colormap mặc định trong Matplotlib là gì?

Colormap mặc định trong Matplotlib là viridis.

Làm thế nào để khắc phục lỗi 'AttributeError: module 'matplotlib' has no attribute 'colormaps'?

Để khắc phục lỗi AttributeError: module 'matplotlib' has no attribute 'colormaps', hãy nâng cấp thư viện Matplotlib lên phiên bản sau 3.4.0.

Làm sao kiểm tra khả năng truy cập của colormap cho người mù màu?

Bạn có thể kiểm tra khả năng truy cập colormap cho người mù màu bằng các công cụ như Coblis (Color Blindness Simulator) hoặc thư viện bên thứ ba như palettable để mô phỏng cách colormap hiển thị với người mù màu.

Colormap đồng nhất theo cảm nhận là gì?

Colormap đồng nhất theo cảm nhận đảm bảo rằng các bước tăng đều trong dữ liệu tương ứng với thay đổi màu được cảm nhận là đều nhau, cho phép diễn giải trực quan chính xác.

Tôi có thể dùng colormap tùy chỉnh từ thư viện bên ngoài trong Matplotlib không?

Có, các thư viện bên ngoài như palettable hoặc cmocean cung cấp colormap tùy chỉnh có thể tích hợp với Matplotlib cho nhu cầu trực quan hóa chuyên biệt.

Chủ đề

Liên quan