python 绘图中设置颜色对比强烈的组合

1 核心函数

给定一个颜色,自动计算对比度最强的颜色

def get_complementary(color):
    # strip the # from the beginning
    color = color[1:]
    # convert the string into hex
    color = int(color, 16)
    # invert the three bytes
    # as good as substracting each of RGB component by 255(FF)
    comp_color = 0xFFFFFF ^ color
    # convert the color back to hex by prefixing a #
    comp_color = "#%06X" % comp_color
    # return the result
    return comp_color

2 举一个完整的例子

如黄色:"#FFFF00"

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

def get_complementary(color):
    # strip the # from the beginning
    color = color[1:]
    # convert the string into hex
    color = int(color, 16)
    # invert the three bytes
    # as good as substracting each of RGB component by 255(FF)
    comp_color = 0xFFFFFF ^ color
    # convert the color back to hex by prefixing a #
    comp_color = "#%06X" % comp_color
    # return the result
    return comp_color

def draw_rectangle(color1):
    color2 = get_complementary(color1)
    #define Matplotlib figure and axis
    fig, ax = plt.subplots()
    #create simple line plot
    ax.plot([0, 10],[0, 10], alpha=0)
    #add rectangle to plot
    ax.add_patch(Rectangle((1, 1), 2, 6,  color=color1))
    ax.add_patch(Rectangle((3, 1), 2, 6, color=color2))
    #display plot
    plt.show()
    print(f"\n----------------------------------------------"
          f"Complementary color of '{color1}' is '{color2}'."
          f"\n----------------------------------------------")

draw_rectangle("#FFFF00") # yellow

3 运行后得到:

----------------------------------------------
Complementary color of '#FFFF00' is '#0000FF'.
----------------------------------------------

在这里插入图片描述

4 颜色表

在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值