使matplotlib中的颜色变暗或变亮 [英] Darken or lighten a color in matplotlib

查看:358
本文介绍了使matplotlib中的颜色变暗或变亮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我在Matplotlib中有一种颜色。也许是字符串('k')或rgb元组((0.5,0.1,0.8))甚至一些十六进制(#05FA2B )。 Matplotlib中是否有命令/便捷功能,该功能可使我加深(或变浅)该颜色。



即是否有 matplotlib.pyplot.darken(c,0.1)或类似的东西?我想我想要的是在幕后将某种颜色进行着色,将其转换为HSL,然后将L值乘以某个给定的因子(以0为底,以1为上限),或明确设置L值返回给定值并返回修改后的颜色。

解决方案

这是



编辑2:删除了函数中不需要的numpy依赖项。



编辑3:通过@FLekschas的改进而修改的功能

  def Adjust_lightness(color ,金额= 0.5):
导入matplotlib.colors作为mc
导入colorsys
试试:
c = mc.cnames [color]
除外:
c = color
c = colorsys.rgb_to_hls(* mc.to_rgb(c))
返回colorsys.hls_to_rgb(c [0],max(0,min(1,数量* c [1])),c [2])


Say I have a color in Matplotlib. Maybe it's a string ('k') or an rgb tuple ((0.5, 0.1, 0.8)) or even some hex (#05FA2B). Is there a command / convenience function in Matplotlib that would allow me to darken (or lighten) that color.

I.e. is there matplotlib.pyplot.darken(c, 0.1) or something like that? I guess what I'm hoping for is something that, behind the scenes, would take a color, convert it to HSL, then either multiply the L value by some given factor (flooring at 0 and capping at 1) or explicitly set the L value to a given value and return the modified color.

解决方案

Here is a function from my gist to lighten any color that I think will work with any color format known to matplotlib. I think setting an amount > 1 might darken too.

def lighten_color(color, amount=0.5):
    """
    Lightens the given color by multiplying (1-luminosity) by the given amount.
    Input can be matplotlib color string, hex string, or RGB tuple.

    Examples:
    >> lighten_color('g', 0.3)
    >> lighten_color('#F034A3', 0.6)
    >> lighten_color((.3,.55,.1), 0.5)
    """
    import matplotlib.colors as mc
    import colorsys
    try:
        c = mc.cnames[color]
    except:
        c = color
    c = colorsys.rgb_to_hls(*mc.to_rgb(c))
    return colorsys.hls_to_rgb(c[0], 1 - amount * (1 - c[1]), c[2])

EDIT: Indeed, it does darken as well as lighten:

import matplotlib.pyplot as plt
import numpy as np

xs = np.linspace(-1, 1, 100)
plt.plot(xs, 0 * xs, color='b', lw=3)
plt.plot(xs, xs**2, color=lighten_color('b', 0.4), lw=3)
plt.plot(xs, -xs**2, color=lighten_color('b', 1.6), lw=3)

Edit 2: Removed un-needed numpy dependency in the function.

Edit 3: Function modified with improvements from @FLekschas

def adjust_lightness(color, amount=0.5):
    import matplotlib.colors as mc
    import colorsys
    try:
        c = mc.cnames[color]
    except:
        c = color
    c = colorsys.rgb_to_hls(*mc.to_rgb(c))
    return colorsys.hls_to_rgb(c[0], max(0, min(1, amount * c[1])), c[2])

这篇关于使matplotlib中的颜色变暗或变亮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆