如何自定義 Matplotlib 中繪圖的顏色和色彩對映
要自定義繪圖的顏色和顏色對映,我們可以使用顏色庫中的 colormap 屬性。我們可以建立兩種型別的顏色對映:(a) 離散顏色對映和 (b) 連續顏色對映。
我們首先要看到如何建立離散顏色對映,然後再建立連續顏色對映。
在示例中,我們將使用“iris”資料集建立三個繪圖,其中第一個繪圖使用預設顏色對映,另外兩個使用 RGB 對映來建立混合色繪圖。然而,我們可以建立與群集一樣多的顏色對映。
示例
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from matplotlib.colors import LinearSegmentedColormap
#Reading the iris dataset
iris = pd.read_csv('iris_dataset.csv', delimiter=',')
iris['species'] = iris['species'].map({"setosa" : 0, "versicolor" :1, "virginica" : 2})
#Defining the figure and its layout
fig, axs = plt.subplots(1,3, figsize=(9,6))
fig.subplots_adjust(left=0.0, bottom=0.05, right=0.9, top=0.95, wspace=0.6)
#Function to plot the graph
def plot_graph(axes, cm, cbaxs):
im = axes.scatter(iris.petal_length, iris.petal_width, s=10*iris.petal_length*iris.petal_width, c=iris.species, cmap = cm)
caxs = plt.axes(cbaxs)
fig.colorbar(im, caxs, ticks=range(3), label='clusetr #')
#Plot the iris dataset clusters with colors chosen from colormap
cbaxs = [0.24, 0.05, 0.03, 0.85] # left, bottom, width and height
plot_graph(axs[0], plt.cm.get_cmap('coolwarm', 3), cbaxs)
#Plot the iris dataset with custom colors RGB
colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1)]
cm = LinearSegmentedColormap.from_list('custom_RGB_cmap', colors,N=3)
#Plot the iris dataset clusters with custom mixed colormaps
cbaxs = [0.58, 0.05, 0.03, 0.85]
plot_graph(axs[1], cm, cbaxs)
colors = [(1, 0.5, 0), (0.25, 0.5, 0.25), (0, 0.5, 1)]
cm = LinearSegmentedColormap.from_list('dummy', colors, N=3)
cbaxs = [0.95, 0.05, 0.03, 0.85]
plot_graph(axs[2], cm, cbaxs)
#Display the plot
plt.show()輸出

廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C #
MongoDB
MySQL
Javascript
PHP