响应式网站建站系统,dede网站mip,做营销的一般逛哪些网站,杭州百度seo代理原文#xff1a;towardsdatascience.com/how-to-convert-a-single-hex-color-code-into-a-monochrome-color-palette-with-python-0bf7741029de 颜色很难#xff0c;尤其是如果你没有设计眼光的话。
大多数我们这些技术专业人士都不是。好处是 Python 可以为你做大部分繁重的…原文towardsdatascience.com/how-to-convert-a-single-hex-color-code-into-a-monochrome-color-palette-with-python-0bf7741029de颜色很难尤其是如果你没有设计眼光的话。大多数我们这些技术专业人士都不是。好处是 Python 可以为你做大部分繁重的工作。它可以生成一个完整的单色调色板任何堆叠图表上看起来都会很惊艳。坏处是要达到这个目的需要相当多的编码。你必须编写自定义函数来将颜色从 HEX 转换为 HSL反之亦然并确定起始颜色是否太亮以及每个下一个颜色应该亮多少。更糟糕的是我还没有找到单个能够完成这个任务的完全工作的 Python 库。正是在这里这篇文章介入了。如果你是我 Substack 的 订阅者你可以跳过阅读下载笔记本 代替。HEX、HSL、RGB – 所有这些术语是什么意思让我们快速了解一下你需要了解的三种颜色格式HEX– 通常用于网页开发和图形设计的一个六位数代码。颜色代码以#开头后面跟着六个十六进制数字。成对的两个数字代表红色、绿色和蓝色的数量。例如#FF5633–FF代表红色56代表绿色33代表蓝色。十六进制值可以从00到FF或十进制的 0 到 255。RGB– 一种基于红色、绿色和蓝色成分定义颜色的颜色模型。每个值从 0 到 255。不同量的红色、绿色和蓝色组合可以产生广泛的颜色。它可以很容易地转换为 HEX – 只需将 RGB 数量转换为它们的十六进制表示。HSL– 颜色的圆柱坐标表示。它根据色调、饱和度和亮度来描述颜色。色调是颜色本身在色轮上表示为一个角度0 到 360 度0 度为红色120 度为绿色240 度为蓝色。饱和度表示颜色的鲜艳程度用百分比表示0–100%。亮度表示颜色的明暗程度0% 为黑色100% 为白色。创建单色调色板的过程可以归结为在保持色调和饱和度不变的情况下调整 HSL 格式中的颜色亮度。为了更好地理解尝试任何在线的颜色轮工具。输入一个 HEX 代码你将看到其其他颜色系统版本https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/e02bb8a5f08e58b44ce0961f95eb8121.png图像 1 – 不同颜色模型中的十六进制颜色代码图片由作者提供但要达到这个目标你需要将十六进制颜色转换为 RGB将 RGB 转换为 HSL获取不同亮度百分比的色彩数组然后将它们转换回十六进制。问题在于某些颜色代码无法 100%准确地转换将被估算。这没关系因为你最终会得到一个视觉上难以区分的颜色其十六进制代码略有不同。理论就到这里吧——让我们开始编码如何从头创建单色色彩调色板首先导入库importnumpyasnpimportpandasaspdimportmatplotlibasmplimportmatplotlib.pyplotasplt你可以选择使用我的自定义 Matplotlib 主题来使图表突出无需手动调整mpl.style.use(custom_light.mplstyle)现在开始编写代码。MonochromePaletteGenerator类实现了以下方法__init__()– 类构造函数初始化两个属性MIN_ALLOWED_LIGHTNESS设置为 15 的整数以确保调色板不会以过浅的颜色开始和max_palette_lightness设置为 95 的整数它限制了调色板中最亮颜色的亮度。__validate_starting_lightness()– 检查起始亮度值是否与构造函数中设置的范围内匹配。hex_to_hxl()– 给定十六进制颜色代码它首先将其转换为 RGB然后通过一个相对复杂的过程计算亮度、饱和度和色调。hsl_to_hex()– 给定色调、饱和度和亮度的值该方法通过素数估算 RGB 值然后将它们转换回十六进制颜色代码。__create_lightness_range()– 一个辅助方法用于创建具有线性分布亮度的n_colors单色色彩调色板。你可能需要调整此方法以调整颜色之间的间距例如不要使用线性间距。create_hex_code_palette()– 给定起始十六进制颜色代码和颜色数量它将十六进制转换为 HSL创建亮度范围并将 HSL 颜色列表转换为十六进制格式。create_matplotlib_palette()– 使用 Matplotlib 的mpl.colors.ListedColormap创建一个可以在 Matplotlib 中使用的色彩调色板。这就是代码中的核心内容classMonochromePaletteGenerator:def__init__(self,max_palette_lightness:int95):self.MIN_ALLOWED_LIGHTNESS15self.max_palette_lightnessmax_palette_lightnessdef__validate_starting_lightness(self,starting_lightness:int)-bool:ifstarting_lightnessself.MIN_ALLOWED_LIGHTNESS:returnTruereturnFalsestaticmethoddefhex_to_hsl(hex_color:str)-tuple:# Remove the # character if presenthex_colorhex_color.lstrip(#)# Convert hex to RGBrint(hex_color[0:2],16)/255.0gint(hex_color[2:4],16)/255.0bint(hex_color[4:6],16)/255.0# Find the maximum and minimum RGB valuesmax_valmax(r,g,b)min_valmin(r,g,b)deltamax_val-min_val# Calculate LightnessL(max_valmin_val)/2# Calculate Saturationifdelta0:S0# Its a shade of gray, so no saturationH0# Hue is undefined for gray, but we can set it to 0else:ifL0.5:Sdelta/(max_valmin_val)else:Sdelta/(2.0-max_val-min_val)# Calculate Hueifmax_valr:H((g-b)/delta)%6elifmax_valg:H(b-r)/delta2elifmax_valb:H(r-g)/delta4H*60# Convert hue to degreesifH0:H360returnint(round(H)),int(round(S*100)),int(round(L*100))staticmethoddefhsl_to_hex(h:int,s:int,l:int)-str:# Convert the saturation and lightness percentages to a fraction of 1s/100l/100# Calculate C, X, and mC(1-abs(2*l-1))*s# ChromaXC*(1-abs((h/60)%2-1))# Intermediate value based on hueml-C/2# Lightness adjustment# Calculate r, g, b (primed values)if0h60:r_prime,g_prime,b_primeC,X,0elif60h120:r_prime,g_prime,b_primeX,C,0elif120h180:r_prime,g_prime,b_prime0,C,Xelif180h240:r_prime,g_prime,b_prime0,X,Celif240h300:r_prime,g_prime,b_primeX,0,Celif300h360:r_prime,g_prime,b_primeC,0,Xelse:raiseValueError(Hue value must be in range [0, 360))# Convert r, g, b to the range [0, 255]rround((r_primem)*255)ground((g_primem)*255)bround((b_primem)*255)# Convert RGB to hexreturn#{:02X}{:02X}{:02X}.format(r,g,b)def__create_lightness_range(self,starting_lightness:int,n_colors:int)-list:# Make n_colors number of linearly spaced lightness values between thr provided starting color# and max allowed lightnessspaced_valuesnp.linspace(starting_lightness,self.max_palette_lightness,n_colors)lightnessnp.round(spaced_values).astype(int)returnlightnessdefcreate_hex_code_palette(self,starting_hex:str,n_colors:int)-list:# Convert HEX to HSLstarting_hslself.hex_to_hsl(hex_colorstarting_hex)# Check if HSL is validis_valid_starting_hexself.__validate_starting_lightness(starting_lightnessstarting_hsl[2])# Proceed only if the starting HSL is validifis_valid_starting_hex:palette[]lightness_rangeself.__create_lightness_range(starting_lightnessstarting_hsl[2],n_colorsn_colors)forlightnessinlightness_range:# Keep hue and saturation identicalhstarting_hsl[0]sstarting_hsl[1]# Only change the lightnesscurr_hexself.hsl_to_hex(hh,ss,llightness)palette.append(curr_hex)returnpaletteraiseValueError(Given starting color is too light to construct a palette. Please choose a darker shade.)staticmethoddefcreate_matplotlib_palette(colors:list,palette_name:str)-mpl.colors.ListedColormap:returnmpl.colors.ListedColormap(namepalette_name,colorscolors)接下来让我们看看如何使用这个类。如何使用 MonochromePaletteGenerator 类你可以像通常一样从类中创建对象palette_generatorMonochromePaletteGenerator()无需参数因为max_palette_lightness有默认值。要创建一个单色蓝色调色板提供一个足够暗的起始十六进制颜色代码和颜色数量。从那里你还可以将生成的调色板转换为 Matplotlib 格式monochrome_bluepalette_generator.create_hex_code_palette(starting_hex#051923,n_colors10)monochrome_blue_mplpalette_generator.create_matplotlib_palette(colorsmonochrome_blue,palette_namecustom-monochrome-blue)print(monochrome_blue)monochrome_blue_mplhttps://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/6f020c0a10bbaf5de36cc4aef0d66196.png图像 2 – 单色蓝色调色板作者提供它也适用于其他颜色。例如你可以使用以下代码片段创建单色红色调色板monochrome_redpalette_generator.create_hex_code_palette(starting_hex#1c0000,n_colors7)monochrome_red_mplpalette_generator.create_matplotlib_palette(colorsmonochrome_red,palette_namecustom-monochrome-red)print(monochrome_red)monochrome_red_mplhttps://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/177bcfc864a679f83f41ebb43492171b.png图像 3 – 单色红色调色板作者提供如果起始颜色太亮create_hex_code_palette()函数将失败如下面的示例所示wont_work_greenpalette_generator.create_hex_code_palette(starting_hex#1b663e,n_colors12)https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/9c2a9364a12df23d2a82340a0b5f019e.png图像 4 – 使用过亮起始颜色引发的异常作者提供最好的方式是使用图表来查看你的调色板在实际中的应用。单色调色板在实际中的应用使用以下代码片段来创建一个虚构的员工数量数据集dfpd.DataFrame({HR:[50,63,40,68,35],Engineering:[77,85,62,89,58],Marketing:[50,35,79,43,67],Sales:[59,62,33,77,72],Customer Service:[31,34,61,70,39],Distribution:[35,21,66,90,31],Logistics:[50,54,13,71,32],Production:[22,51,54,28,40],Maintenance:[50,32,61,69,50],Quality Control:[20,21,88,89,39]},index[New York,San Francisco,Los Angeles,Chicago,Miami])dfdf.T dfdf.loc[df.sum(axis1).sort_values().index]dfhttps://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/461dc21ccfa2170903a1ea916b1f364b.png图像 5 – 模拟员工数据集作者提供有 5 个办公地点和 10 个部门——这对于一个堆叠的水平条形图来说是一个理想的情况你可以将自定义调色板传递给colormap参数axdf.plot(kindbarh,colormapmonochrome_blue_mpl,width0.8,edgecolor#000000,stackedTrue)plt.title(Employee Count Per Location And Department,locleft,fontdict{weight:bold},y1.06)plt.xlabel(Office Location)plt.ylabel(Count)plt.show()https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/2d1cfdec786afc25afe5574a2711c52e.png图像 6 – 使用蓝色单色调色板的图表作者提供同样的代码也可以用于单色红色调色板——只需更改colormap的值axdf.plot(kindbarh,colormapmonochrome_red_mpl,width0.8,edgecolor#000000,stackedTrue)plt.title(Employee Count Per Location And Department,locleft,fontdict{weight:bold},y1.06)plt.xlabel(Office Location)plt.ylabel(Count)plt.show()https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/c25fdaf36170252b7b197f02dd8ee449.png图像 7 – 使用红色单色调色板的图表作者提供简而言之——它工作得非常出色——只需要一个足够暗的颜色来开始。总结总结来说一点 Python 代码就能走得很远。通常要创建单色调色板你会在网上搜索或者从一个你喜欢的颜色开始调整亮度直到得到足够的变体。今天你已经学会了如何自动化这个过程。你可以通过添加默认的起始颜色来扩展这个功能这样你就不需要每次都选择一个。但那部分很简单我就留给你了。到此为止。-达里奥想要提升你的数据可视化技能加入我的 Substack与成千上万志同道合的人一起获取专家建议和独家内容。使用 Python 进行数据涂鸦 | 达里奥·拉德齐奇 | Substack最初发布于darioradecic.substack.com。