首页 > 解决方案 > 尝试创建自定义颜色映射时出现类型错误

问题描述

我正在尝试创建两种颜色的映射,但不断收到此错误:

类型错误:to_rgb() 缺少 1 个必需的位置参数:'c'

我试过搜索这个,但遇到了麻烦,所以我来到了这里。任何帮助,将不胜感激!

import numpy as np 
import pandas as pd 
import pickle    
import matplotlib
import matplotlib.pyplot as plt
color_map = plt.cm.winter
from matplotlib.patches import RegularPolygon
import math
from PIL import Image
# Needed for custom colour mapping
from matplotlib.colors import ListedColormap,LinearSegmentedColormap
import matplotlib.colors as mcolors

c = mcolors.ColorConverter().to_rgb()
positive_cm = ListedColormap([c('#e1e5e5'),c('#d63b36')])
negative_cm = ListedColormap([c('#e1e5e5'),c('#28aee4')])

标签: pythonmatplotlib

解决方案


根据以下文档matplotlib

https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.colors.to_rgb.html

您需要将颜色作为参数传递给to_rgb函数。如果您的意图是将该函数分配给c,那么您需要做的就是删除括号,这样您就不会尝试实际调用它(没有参数):

c = mcolors.ColorConverter().to_rgb

我可能会建议让它保留一个更有意义的名称(并可能清理其中一些导入):

from matplotlib import colors

ListedColorMap = colors.ListedColorMap
to_rgb = colors.ColorConverter().to_rgb

positive_cm = ListedColormap([to_rgb('#e1e5e5'), to_rgb('#d63b36')])
negative_cm = ListedColormap([to_rgb('#e1e5e5'), to_rgb('#28aee4')])

推荐阅读