[英]Matplotlib\Seaborn wrong colors on float data with custom colormap
小於等於 1000/60 (16.6667) 的值必須具有從藍色到綠色的漸變。 大於 1000/60 (16.6667) 的值必須具有從紅色到黑色的漸變。 但是從 16.67 到 16.70 的值是藍色而不是紅色。 為什么? 如何讓它們變紅?
import glob
import os
import subprocess
import sys
import matplotlib.colors
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from PIL import Image, ImageEnhance, ImageChops, ImageDraw, ImageFilter
Image.MAX_IMAGE_PIXELS = None
pd.options.display.float_format = '{:.2f}'.format
np.set_printoptions(suppress=True, precision=2)
# Open image in end
def openImage(path):
imageViewerFromCommandLine = {'linux': 'xdg-open',
'win32': 'explorer',
'darwin': 'open'}[sys.platform]
subprocess.run([imageViewerFromCommandLine, path])
test_data = np.arange(16.60, 16.81, 0.01)
test_data = np.resize(test_data, (3, 7))
line_legend = (1000 / 29, 16.66, 16.00, 0)
line_legend_last = len(line_legend) - 1
# norm for colormap from 0 to 1000/29
norm = matplotlib.colors.Normalize(line_legend[line_legend_last], line_legend[0], clip=True)
# custom colors
colors = [[0.0, "lime"],
[norm(16.00), "green"],
[norm(16.66), "blue"],
[norm(16.67), "red"],
[1.0, "black"]]
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", colors)
# color bar range and labels
cbar_kws = {"orientation": "vertical",
"shrink": 1,
'extend': 'both',
"ticks": line_legend,
"drawedges": False,
}
ax = sns.heatmap(test_data, linewidths=0.1, linecolor='gainsboro', cmap=cmap, xticklabels=1, yticklabels=1, square=True,
cbar=True, annot=True, fmt='g', cbar_kws=cbar_kws, robust=True,
vmin=line_legend[line_legend_last], vmax=line_legend[0])
plt.savefig(r'D:\result_wrong_colors.png')
openImage(r'D:\result_wrong_colors.png')
圖像結果
在內部,顏色圖由顏色列表表示。 默認情況下,該列表中有 256 種顏色。 LinearSegmentedColormap.from_list
有一個參數N=
來設置不同數量的顏色。 根據您需要的顏色范圍有多精確,您需要更大的數字。
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", colors, N=10000)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.