Hướng dẫn how to define colors in python - cách xác định màu sắc trong python

Tùy thuộc vào cách bạn dự định sử dụng các giá trị, bạn có nhiều tùy chọn:

colorString = "#920310"
colorList   = [0x93, 0x03, 0x10] 
colorTuple  = (0x93, 0x03, 0x10)
colorDict   = {
   "R" : 0x93,
   "G" : 0x03,
   "B" : 0x10,
}

Hoặc, nếu bạn dự định có một số hoạt động để đối phó với màu sắc của mình, hãy nói chuyển đổi sang các định dạng khác nhau, bạn có thể xác định một lớp màu:

class Color(object):
    def __init__(self, r, g, b):
        self._color = (r,g,b)

    def get_tuple(self):
        return self._color

    def get_str(self):
        return "#%02X%02X%02X" % self._color

    def __str__(self):
        return self.get_str()

    def get_YUV(self):
        # ...

Ví dụ sử dụng:

>>> a = Color(0x93, 0x03, 0xAA) # set using hex
>>> print a
#9303AA
>>> b = Color(12, 123, 3) # set using int
>>> print b
#0C7B03

Ghi chú

Đây là chu kỳ màu mặc định.here to download the full example code

Thông số màu "CN" trong đó

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

th = np.linspace(0, 2*np.pi, 128)


def demo(sty):
    mpl.style.use(sty)
    fig, ax = plt.subplots(figsize=(3, 3))

    ax.set_title('style: {!r}'.format(sty), color='C0')

    ax.plot(th, np.cos(th), 'C1', label='C1')
    ax.plot(th, np.sin(th), 'C2', label='C2')
    ax.legend()


demo('default')
demo('seaborn-v0_8')
1 đi trước một số đóng vai trò là một chỉ mục vào chu kỳ thuộc tính mặc định.

Matplotlib chỉ mục màu tại thời điểm vẽ và mặc định là màu đen nếu chu kỳ không bao gồm màu.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

th = np.linspace(0, 2*np.pi, 128)


def demo(sty):
    mpl.style.use(sty)
    fig, ax = plt.subplots(figsize=(3, 3))

    ax.set_title('style: {!r}'.format(sty), color='C0')

    ax.plot(th, np.cos(th), 'C1', label='C1')
    ax.plot(th, np.sin(th), 'C2', label='C2')
    ax.legend()


demo('default')
demo('seaborn-v0_8')
4 (mặc định:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

th = np.linspace(0, 2*np.pi, 128)


def demo(sty):
    mpl.style.use(sty)
    fig, ax = plt.subplots(figsize=(3, 3))

    ax.set_title('style: {!r}'.format(sty), color='C0')

    ax.plot(th, np.cos(th), 'C1', label='C1')
    ax.plot(th, np.sin(th), 'C2', label='C2')
    ax.legend()


demo('default')
demo('seaborn-v0_8')
5)

"Red", "Green" và "Blue" là cường độ của những màu sắc đó. Kết hợp, chúng đại diện cho không gian màu.

  • (0.1, 0.2, 0.5)

  • (0.1, 0.2, 0.5, 0.3)

Matplotlib thu hút các nghệ sĩ dựa trên tham số

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

th = np.linspace(0, 2*np.pi, 128)


def demo(sty):
    mpl.style.use(sty)
    fig, ax = plt.subplots(figsize=(3, 3))

    ax.set_title('style: {!r}'.format(sty), color='C0')

    ax.plot(th, np.cos(th), 'C1', label='C1')
    ax.plot(th, np.sin(th), 'C2', label='C2')
    ax.legend()


demo('default')
demo('seaborn-v0_8')
6. Nếu không có giá trị được chỉ định, matplotlib mặc định theo thứ tự của các nghệ sĩ được thêm vào các trục.

  • '#0f0f0f'

  • '#0f0f0f80'

Alpha cho một nghệ sĩ kiểm soát độ mờ đục. Nó chỉ ra cách màu RGB của nghệ sĩ mới kết hợp với các màu RGB đã có trên các trục.

  • Hai nghệ sĩ kết hợp với tổng hợp alpha. Matplotlib sử dụng phương trình dưới đây để tính toán kết quả pha trộn một nghệ sĩ mới.

  • Alpha của 1 cho biết nghệ sĩ mới hoàn toàn bao phủ màu sắc trước đó. Alpha của 0 cho màu trên cùng không hiển thị; Tuy nhiên, nó góp phần pha trộn cho các giá trị trung gian là kết quả tích lũy của tất cả các nghệ sĩ trước đó. Bảng sau đây chứa các ví dụ.

Giá trị alpha

  • Trực quan

  • Các nghệ sĩ đặt hàng lại không giao hoán trong matplotlib.

  • Lựa chọn màu "cn"#

Matplotlib chuyển đổi màu "CN" thành RGBA khi vẽ các nghệ sĩ. Kiểu dáng với phần Cycler chứa thông tin bổ sung về việc kiểm soát màu sắc và thuộc tính kiểu.

Ghi chú

Màu đầu tiên

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

th = np.linspace(0, 2*np.pi, 128)


def demo(sty):
    mpl.style.use(sty)
    fig, ax = plt.subplots(figsize=(3, 3))

    ax.set_title('style: {!r}'.format(sty), color='C0')

    ax.plot(th, np.cos(th), 'C1', label='C1')
    ax.plot(th, np.sin(th), 'C2', label='C2')
    ax.legend()


demo('default')
demo('seaborn-v0_8')
2 là tiêu đề. Mỗi ô sử dụng màu thứ hai và thứ ba của mỗi kiểu
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

th = np.linspace(0, 2*np.pi, 128)


def demo(sty):
    mpl.style.use(sty)
    fig, ax = plt.subplots(figsize=(3, 3))

    ax.set_title('style: {!r}'.format(sty), color='C0')

    ax.plot(th, np.cos(th), 'C1', label='C1')
    ax.plot(th, np.sin(th), 'C2', label='C2')
    ax.legend()


demo('default')
demo('seaborn-v0_8')
4 (mặc định:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

th = np.linspace(0, 2*np.pi, 128)


def demo(sty):
    mpl.style.use(sty)
    fig, ax = plt.subplots(figsize=(3, 3))

    ax.set_title('style: {!r}'.format(sty), color='C0')

    ax.plot(th, np.cos(th), 'C1', label='C1')
    ax.plot(th, np.sin(th), 'C2', label='C2')
    ax.legend()


demo('default')
demo('seaborn-v0_8')
5). Chúng lần lượt là
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

th = np.linspace(0, 2*np.pi, 128)


def demo(sty):
    mpl.style.use(sty)
    fig, ax = plt.subplots(figsize=(3, 3))

    ax.set_title('style: {!r}'.format(sty), color='C0')

    ax.plot(th, np.cos(th), 'C1', label='C1')
    ax.plot(th, np.sin(th), 'C2', label='C2')
    ax.legend()


demo('default')
demo('seaborn-v0_8')
3 và
import matplotlib.colors as mcolors
import matplotlib.patches as mpatch

overlap = {name for name in mcolors.CSS4_COLORS
           if f'xkcd:{name}' in mcolors.XKCD_COLORS}

fig = plt.figure(figsize=[9, 5])
ax = fig.add_axes([0, 0, 1, 1])

n_groups = 3
n_rows = len(overlap) // n_groups + 1

for j, color_name in enumerate(sorted(overlap)):
    css4 = mcolors.CSS4_COLORS[color_name]
    xkcd = mcolors.XKCD_COLORS[f'xkcd:{color_name}'].upper()

    # Pick text colour based on perceived luminance.
    rgba = mcolors.to_rgba_array([css4, xkcd])
    luma = 0.299 * rgba[:, 0] + 0.587 * rgba[:, 1] + 0.114 * rgba[:, 2]
    css4_text_color = 'k' if luma[0] > 0.5 else 'w'
    xkcd_text_color = 'k' if luma[1] > 0.5 else 'w'

    col_shift = (j // n_rows) * 3
    y_pos = j % n_rows
    text_args = dict(fontsize=10, weight='bold' if css4 == xkcd else None)
    ax.add_patch(mpatch.Rectangle((0 + col_shift, y_pos), 1, 1, color=css4))
    ax.add_patch(mpatch.Rectangle((1 + col_shift, y_pos), 1, 1, color=xkcd))
    ax.text(0.5 + col_shift, y_pos + .7, css4,
            color=css4_text_color, ha='center', **text_args)
    ax.text(1.5 + col_shift, y_pos + .7, xkcd,
            color=xkcd_text_color, ha='center', **text_args)
    ax.text(2 + col_shift, y_pos + .7, f'  {color_name}', **text_args)

for g in range(n_groups):
    ax.hlines(range(n_rows), 3*g, 3*g + 2.8, color='0.7', linewidth=1)
    ax.text(0.5 + 3*g, -0.3, 'X11/CSS4', ha='center')
    ax.text(1.5 + 3*g, -0.3, 'xkcd', ha='center')

ax.set_xlim(0, 3 * n_groups)
ax.set_ylim(n_rows, -1)
ax.axis('off')

plt.show()
3.

  • So sánh giữa các màu X11/CSS4 và XKCD#

  • Màu sắc XKCD đến từ một cuộc khảo sát người dùng được thực hiện bởi XKCD Webcomic.

  • 95 trong số các tên màu 148 X11/CSS4 cũng xuất hiện trong Khảo sát màu XKCD. Hầu như tất cả chúng đều ánh xạ tới các giá trị màu khác nhau trong X11/CSS4 và trong bảng màu XKCD. Chỉ có 'đen', 'trắng' và 'cyan' là giống hệt nhau.

  • Ví dụ,

    import matplotlib.colors as mcolors
    import matplotlib.patches as mpatch
    
    overlap = {name for name in mcolors.CSS4_COLORS
               if f'xkcd:{name}' in mcolors.XKCD_COLORS}
    
    fig = plt.figure(figsize=[9, 5])
    ax = fig.add_axes([0, 0, 1, 1])
    
    n_groups = 3
    n_rows = len(overlap) // n_groups + 1
    
    for j, color_name in enumerate(sorted(overlap)):
        css4 = mcolors.CSS4_COLORS[color_name]
        xkcd = mcolors.XKCD_COLORS[f'xkcd:{color_name}'].upper()
    
        # Pick text colour based on perceived luminance.
        rgba = mcolors.to_rgba_array([css4, xkcd])
        luma = 0.299 * rgba[:, 0] + 0.587 * rgba[:, 1] + 0.114 * rgba[:, 2]
        css4_text_color = 'k' if luma[0] > 0.5 else 'w'
        xkcd_text_color = 'k' if luma[1] > 0.5 else 'w'
    
        col_shift = (j // n_rows) * 3
        y_pos = j % n_rows
        text_args = dict(fontsize=10, weight='bold' if css4 == xkcd else None)
        ax.add_patch(mpatch.Rectangle((0 + col_shift, y_pos), 1, 1, color=css4))
        ax.add_patch(mpatch.Rectangle((1 + col_shift, y_pos), 1, 1, color=xkcd))
        ax.text(0.5 + col_shift, y_pos + .7, css4,
                color=css4_text_color, ha='center', **text_args)
        ax.text(1.5 + col_shift, y_pos + .7, xkcd,
                color=xkcd_text_color, ha='center', **text_args)
        ax.text(2 + col_shift, y_pos + .7, f'  {color_name}', **text_args)
    
    for g in range(n_groups):
        ax.hlines(range(n_rows), 3*g, 3*g + 2.8, color='0.7', linewidth=1)
        ax.text(0.5 + 3*g, -0.3, 'X11/CSS4', ha='center')
        ax.text(1.5 + 3*g, -0.3, 'xkcd', ha='center')
    
    ax.set_xlim(0, 3 * n_groups)
    ax.set_ylim(n_rows, -1)
    ax.axis('off')
    
    plt.show()
    
    4 bản đồ đến
    import matplotlib.colors as mcolors
    import matplotlib.patches as mpatch
    
    overlap = {name for name in mcolors.CSS4_COLORS
               if f'xkcd:{name}' in mcolors.XKCD_COLORS}
    
    fig = plt.figure(figsize=[9, 5])
    ax = fig.add_axes([0, 0, 1, 1])
    
    n_groups = 3
    n_rows = len(overlap) // n_groups + 1
    
    for j, color_name in enumerate(sorted(overlap)):
        css4 = mcolors.CSS4_COLORS[color_name]
        xkcd = mcolors.XKCD_COLORS[f'xkcd:{color_name}'].upper()
    
        # Pick text colour based on perceived luminance.
        rgba = mcolors.to_rgba_array([css4, xkcd])
        luma = 0.299 * rgba[:, 0] + 0.587 * rgba[:, 1] + 0.114 * rgba[:, 2]
        css4_text_color = 'k' if luma[0] > 0.5 else 'w'
        xkcd_text_color = 'k' if luma[1] > 0.5 else 'w'
    
        col_shift = (j // n_rows) * 3
        y_pos = j % n_rows
        text_args = dict(fontsize=10, weight='bold' if css4 == xkcd else None)
        ax.add_patch(mpatch.Rectangle((0 + col_shift, y_pos), 1, 1, color=css4))
        ax.add_patch(mpatch.Rectangle((1 + col_shift, y_pos), 1, 1, color=xkcd))
        ax.text(0.5 + col_shift, y_pos + .7, css4,
                color=css4_text_color, ha='center', **text_args)
        ax.text(1.5 + col_shift, y_pos + .7, xkcd,
                color=xkcd_text_color, ha='center', **text_args)
        ax.text(2 + col_shift, y_pos + .7, f'  {color_name}', **text_args)
    
    for g in range(n_groups):
        ax.hlines(range(n_rows), 3*g, 3*g + 2.8, color='0.7', linewidth=1)
        ax.text(0.5 + 3*g, -0.3, 'X11/CSS4', ha='center')
        ax.text(1.5 + 3*g, -0.3, 'xkcd', ha='center')
    
    ax.set_xlim(0, 3 * n_groups)
    ax.set_ylim(n_rows, -1)
    ax.axis('off')
    
    plt.show()
    
    5 trong khi
    import matplotlib.colors as mcolors
    import matplotlib.patches as mpatch
    
    overlap = {name for name in mcolors.CSS4_COLORS
               if f'xkcd:{name}' in mcolors.XKCD_COLORS}
    
    fig = plt.figure(figsize=[9, 5])
    ax = fig.add_axes([0, 0, 1, 1])
    
    n_groups = 3
    n_rows = len(overlap) // n_groups + 1
    
    for j, color_name in enumerate(sorted(overlap)):
        css4 = mcolors.CSS4_COLORS[color_name]
        xkcd = mcolors.XKCD_COLORS[f'xkcd:{color_name}'].upper()
    
        # Pick text colour based on perceived luminance.
        rgba = mcolors.to_rgba_array([css4, xkcd])
        luma = 0.299 * rgba[:, 0] + 0.587 * rgba[:, 1] + 0.114 * rgba[:, 2]
        css4_text_color = 'k' if luma[0] > 0.5 else 'w'
        xkcd_text_color = 'k' if luma[1] > 0.5 else 'w'
    
        col_shift = (j // n_rows) * 3
        y_pos = j % n_rows
        text_args = dict(fontsize=10, weight='bold' if css4 == xkcd else None)
        ax.add_patch(mpatch.Rectangle((0 + col_shift, y_pos), 1, 1, color=css4))
        ax.add_patch(mpatch.Rectangle((1 + col_shift, y_pos), 1, 1, color=xkcd))
        ax.text(0.5 + col_shift, y_pos + .7, css4,
                color=css4_text_color, ha='center', **text_args)
        ax.text(1.5 + col_shift, y_pos + .7, xkcd,
                color=xkcd_text_color, ha='center', **text_args)
        ax.text(2 + col_shift, y_pos + .7, f'  {color_name}', **text_args)
    
    for g in range(n_groups):
        ax.hlines(range(n_rows), 3*g, 3*g + 2.8, color='0.7', linewidth=1)
        ax.text(0.5 + 3*g, -0.3, 'X11/CSS4', ha='center')
        ax.text(1.5 + 3*g, -0.3, 'xkcd', ha='center')
    
    ax.set_xlim(0, 3 * n_groups)
    ax.set_ylim(n_rows, -1)
    ax.axis('off')
    
    plt.show()
    
    6 bản đồ đến
    import matplotlib.colors as mcolors
    import matplotlib.patches as mpatch
    
    overlap = {name for name in mcolors.CSS4_COLORS
               if f'xkcd:{name}' in mcolors.XKCD_COLORS}
    
    fig = plt.figure(figsize=[9, 5])
    ax = fig.add_axes([0, 0, 1, 1])
    
    n_groups = 3
    n_rows = len(overlap) // n_groups + 1
    
    for j, color_name in enumerate(sorted(overlap)):
        css4 = mcolors.CSS4_COLORS[color_name]
        xkcd = mcolors.XKCD_COLORS[f'xkcd:{color_name}'].upper()
    
        # Pick text colour based on perceived luminance.
        rgba = mcolors.to_rgba_array([css4, xkcd])
        luma = 0.299 * rgba[:, 0] + 0.587 * rgba[:, 1] + 0.114 * rgba[:, 2]
        css4_text_color = 'k' if luma[0] > 0.5 else 'w'
        xkcd_text_color = 'k' if luma[1] > 0.5 else 'w'
    
        col_shift = (j // n_rows) * 3
        y_pos = j % n_rows
        text_args = dict(fontsize=10, weight='bold' if css4 == xkcd else None)
        ax.add_patch(mpatch.Rectangle((0 + col_shift, y_pos), 1, 1, color=css4))
        ax.add_patch(mpatch.Rectangle((1 + col_shift, y_pos), 1, 1, color=xkcd))
        ax.text(0.5 + col_shift, y_pos + .7, css4,
                color=css4_text_color, ha='center', **text_args)
        ax.text(1.5 + col_shift, y_pos + .7, xkcd,
                color=xkcd_text_color, ha='center', **text_args)
        ax.text(2 + col_shift, y_pos + .7, f'  {color_name}', **text_args)
    
    for g in range(n_groups):
        ax.hlines(range(n_rows), 3*g, 3*g + 2.8, color='0.7', linewidth=1)
        ax.text(0.5 + 3*g, -0.3, 'X11/CSS4', ha='center')
        ax.text(1.5 + 3*g, -0.3, 'xkcd', ha='center')
    
    ax.set_xlim(0, 3 * n_groups)
    ax.set_ylim(n_rows, -1)
    ax.axis('off')
    
    plt.show()
    
    7. Do những vụ va chạm tên này, tất cả các màu XKCD đều có tiền tố
    >>> a = Color(0x93, 0x03, 0xAA) # set using hex
    >>> print a
    #9303AA
    >>> b = Color(12, 123, 3) # set using int
    >>> print b
    #0C7B03
    
    8.

  • Hình ảnh dưới đây cho thấy các vụ va chạm tên. Tên màu nơi các giá trị màu đồng ý in đậm.

  • Tổng thời gian chạy của tập lệnh: (0 phút 1.410 giây)

  • Phòng trưng bày được tạo ra bởi Sphinx-Gallery

  • >>> a = Color(0x93, 0x03, 0xAA) # set using hex
    >>> print a
    #9303AA
    >>> b = Color(12, 123, 3) # set using int
    >>> print b
    #0C7B03
    
    5 như màu trắng

Tên màu X11/CSS4 không nhạy cảm trường hợp không có khoảng trắng.

  • >>> a = Color(0x93, 0x03, 0xAA) # set using hex
    >>> print a
    #9303AA
    >>> b = Color(12, 123, 3) # set using int
    >>> print b
    #0C7B03
    
    6

  • >>> a = Color(0x93, 0x03, 0xAA) # set using hex
    >>> print a
    #9303AA
    >>> b = Color(12, 123, 3) # set using int
    >>> print b
    #0C7B03
    
    7

Tên màu không phân biệt trường hợp từ khảo sát màu XKCD với tiền tố

>>> a = Color(0x93, 0x03, 0xAA) # set using hex
>>> print a
#9303AA
>>> b = Color(12, 123, 3) # set using int
>>> print b
#0C7B03
8.

  • >>> a = Color(0x93, 0x03, 0xAA) # set using hex
    >>> print a
    #9303AA
    >>> b = Color(12, 123, 3) # set using int
    >>> print b
    #0C7B03
    
    9

  • RGB_{new} = RGB_{below} * (1 - \alpha) + RGB_{artist} * \alpha
    
    0

Màu sắc Tableau không nhạy cảm trường hợp từ bảng phân loại 'T10'.

Ghi chú

Đây là chu kỳ màu mặc định.

  • RGB_{new} = RGB_{below} * (1 - \alpha) + RGB_{artist} * \alpha
    
    1

  • RGB_{new} = RGB_{below} * (1 - \alpha) + RGB_{artist} * \alpha
    
    2

  • RGB_{new} = RGB_{below} * (1 - \alpha) + RGB_{artist} * \alpha
    
    3

  • RGB_{new} = RGB_{below} * (1 - \alpha) + RGB_{artist} * \alpha
    
    4

  • RGB_{new} = RGB_{below} * (1 - \alpha) + RGB_{artist} * \alpha
    
    5

  • RGB_{new} = RGB_{below} * (1 - \alpha) + RGB_{artist} * \alpha
    
    6

  • RGB_{new} = RGB_{below} * (1 - \alpha) + RGB_{artist} * \alpha
    
    7

  • RGB_{new} = RGB_{below} * (1 - \alpha) + RGB_{artist} * \alpha
    
    8

  • RGB_{new} = RGB_{below} * (1 - \alpha) + RGB_{artist} * \alpha
    
    9

  • import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    
    th = np.linspace(0, 2*np.pi, 128)
    
    
    def demo(sty):
        mpl.style.use(sty)
        fig, ax = plt.subplots(figsize=(3, 3))
    
        ax.set_title('style: {!r}'.format(sty), color='C0')
    
        ax.plot(th, np.cos(th), 'C1', label='C1')
        ax.plot(th, np.sin(th), 'C2', label='C2')
        ax.legend()
    
    
    demo('default')
    demo('seaborn-v0_8')
    
    0

Thông số màu "CN" trong đó

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

th = np.linspace(0, 2*np.pi, 128)


def demo(sty):
    mpl.style.use(sty)
    fig, ax = plt.subplots(figsize=(3, 3))

    ax.set_title('style: {!r}'.format(sty), color='C0')

    ax.plot(th, np.cos(th), 'C1', label='C1')
    ax.plot(th, np.sin(th), 'C2', label='C2')
    ax.legend()


demo('default')
demo('seaborn-v0_8')
1 đi trước một số đóng vai trò là một chỉ mục vào chu kỳ thuộc tính mặc định.

Ghi chú

Đây là chu kỳ màu mặc định.

  • import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    
    th = np.linspace(0, 2*np.pi, 128)
    
    
    def demo(sty):
        mpl.style.use(sty)
        fig, ax = plt.subplots(figsize=(3, 3))
    
        ax.set_title('style: {!r}'.format(sty), color='C0')
    
        ax.plot(th, np.cos(th), 'C1', label='C1')
        ax.plot(th, np.sin(th), 'C2', label='C2')
        ax.legend()
    
    
    demo('default')
    demo('seaborn-v0_8')
    
    2

  • import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    
    th = np.linspace(0, 2*np.pi, 128)
    
    
    def demo(sty):
        mpl.style.use(sty)
        fig, ax = plt.subplots(figsize=(3, 3))
    
        ax.set_title('style: {!r}'.format(sty), color='C0')
    
        ax.plot(th, np.cos(th), 'C1', label='C1')
        ax.plot(th, np.sin(th), 'C2', label='C2')
        ax.legend()
    
    
    demo('default')
    demo('seaborn-v0_8')
    
    3

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

th = np.linspace(0, 2*np.pi, 128)


def demo(sty):
    mpl.style.use(sty)
    fig, ax = plt.subplots(figsize=(3, 3))

    ax.set_title('style: {!r}'.format(sty), color='C0')

    ax.plot(th, np.cos(th), 'C1', label='C1')
    ax.plot(th, np.sin(th), 'C2', label='C2')
    ax.legend()


demo('default')
demo('seaborn-v0_8')
4 (mặc định:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

th = np.linspace(0, 2*np.pi, 128)


def demo(sty):
    mpl.style.use(sty)
    fig, ax = plt.subplots(figsize=(3, 3))

    ax.set_title('style: {!r}'.format(sty), color='C0')

    ax.plot(th, np.cos(th), 'C1', label='C1')
    ax.plot(th, np.sin(th), 'C2', label='C2')
    ax.legend()


demo('default')
demo('seaborn-v0_8')
5)

"Red", "Green" và "Blue" là cường độ của những màu sắc đó. Kết hợp, chúng đại diện cho không gian màu.

Matplotlib thu hút các nghệ sĩ dựa trên tham số

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

th = np.linspace(0, 2*np.pi, 128)


def demo(sty):
    mpl.style.use(sty)
    fig, ax = plt.subplots(figsize=(3, 3))

    ax.set_title('style: {!r}'.format(sty), color='C0')

    ax.plot(th, np.cos(th), 'C1', label='C1')
    ax.plot(th, np.sin(th), 'C2', label='C2')
    ax.legend()


demo('default')
demo('seaborn-v0_8')
6. Nếu không có giá trị được chỉ định, matplotlib mặc định theo thứ tự của các nghệ sĩ được thêm vào các trục.

Alpha cho một nghệ sĩ kiểm soát độ mờ đục. Nó chỉ ra cách màu RGB của nghệ sĩ mới kết hợp với các màu RGB đã có trên các trục.

Hai nghệ sĩ kết hợp với tổng hợp alpha. Matplotlib sử dụng phương trình dưới đây để tính toán kết quả pha trộn một nghệ sĩ mới.

RGB_{new} = RGB_{below} * (1 - \alpha) + RGB_{artist} * \alpha

Alpha của 1 cho biết nghệ sĩ mới hoàn toàn bao phủ màu sắc trước đó. Alpha của 0 cho màu trên cùng không hiển thị; Tuy nhiên, nó góp phần pha trộn cho các giá trị trung gian là kết quả tích lũy của tất cả các nghệ sĩ trước đó. Bảng sau đây chứa các ví dụ.

Giá trị alpha

Trực quan

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

th = np.linspace(0, 2*np.pi, 128)


def demo(sty):
    mpl.style.use(sty)
    fig, ax = plt.subplots(figsize=(3, 3))

    ax.set_title('style: {!r}'.format(sty), color='C0')

    ax.plot(th, np.cos(th), 'C1', label='C1')
    ax.plot(th, np.sin(th), 'C2', label='C2')
    ax.legend()


demo('default')
demo('seaborn-v0_8')
7

Hướng dẫn how to define colors in python - cách xác định màu sắc trong python

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

th = np.linspace(0, 2*np.pi, 128)


def demo(sty):
    mpl.style.use(sty)
    fig, ax = plt.subplots(figsize=(3, 3))

    ax.set_title('style: {!r}'.format(sty), color='C0')

    ax.plot(th, np.cos(th), 'C1', label='C1')
    ax.plot(th, np.sin(th), 'C2', label='C2')
    ax.legend()


demo('default')
demo('seaborn-v0_8')
8

Hướng dẫn how to define colors in python - cách xác định màu sắc trong python

Ghi chú

Các nghệ sĩ đặt hàng lại không giao hoán trong matplotlib.

Lựa chọn màu "cn"#

Matplotlib chuyển đổi màu "CN" thành RGBA khi vẽ các nghệ sĩ. Kiểu dáng với phần Cycler chứa thông tin bổ sung về việc kiểm soát màu sắc và thuộc tính kiểu.Styling with cycler section contains additional information about controlling colors and style properties.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

th = np.linspace(0, 2*np.pi, 128)


def demo(sty):
    mpl.style.use(sty)
    fig, ax = plt.subplots(figsize=(3, 3))

    ax.set_title('style: {!r}'.format(sty), color='C0')

    ax.plot(th, np.cos(th), 'C1', label='C1')
    ax.plot(th, np.sin(th), 'C2', label='C2')
    ax.legend()


demo('default')
demo('seaborn-v0_8')

Màu đầu tiên

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

th = np.linspace(0, 2*np.pi, 128)


def demo(sty):
    mpl.style.use(sty)
    fig, ax = plt.subplots(figsize=(3, 3))

    ax.set_title('style: {!r}'.format(sty), color='C0')

    ax.plot(th, np.cos(th), 'C1', label='C1')
    ax.plot(th, np.sin(th), 'C2', label='C2')
    ax.legend()


demo('default')
demo('seaborn-v0_8')
2 là tiêu đề. Mỗi ô sử dụng màu thứ hai và thứ ba của mỗi kiểu
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

th = np.linspace(0, 2*np.pi, 128)


def demo(sty):
    mpl.style.use(sty)
    fig, ax = plt.subplots(figsize=(3, 3))

    ax.set_title('style: {!r}'.format(sty), color='C0')

    ax.plot(th, np.cos(th), 'C1', label='C1')
    ax.plot(th, np.sin(th), 'C2', label='C2')
    ax.legend()


demo('default')
demo('seaborn-v0_8')
4 (mặc định:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

th = np.linspace(0, 2*np.pi, 128)


def demo(sty):
    mpl.style.use(sty)
    fig, ax = plt.subplots(figsize=(3, 3))

    ax.set_title('style: {!r}'.format(sty), color='C0')

    ax.plot(th, np.cos(th), 'C1', label='C1')
    ax.plot(th, np.sin(th), 'C2', label='C2')
    ax.legend()


demo('default')
demo('seaborn-v0_8')
5). Chúng lần lượt là
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

th = np.linspace(0, 2*np.pi, 128)


def demo(sty):
    mpl.style.use(sty)
    fig, ax = plt.subplots(figsize=(3, 3))

    ax.set_title('style: {!r}'.format(sty), color='C0')

    ax.plot(th, np.cos(th), 'C1', label='C1')
    ax.plot(th, np.sin(th), 'C2', label='C2')
    ax.legend()


demo('default')
demo('seaborn-v0_8')
3 và
import matplotlib.colors as mcolors
import matplotlib.patches as mpatch

overlap = {name for name in mcolors.CSS4_COLORS
           if f'xkcd:{name}' in mcolors.XKCD_COLORS}

fig = plt.figure(figsize=[9, 5])
ax = fig.add_axes([0, 0, 1, 1])

n_groups = 3
n_rows = len(overlap) // n_groups + 1

for j, color_name in enumerate(sorted(overlap)):
    css4 = mcolors.CSS4_COLORS[color_name]
    xkcd = mcolors.XKCD_COLORS[f'xkcd:{color_name}'].upper()

    # Pick text colour based on perceived luminance.
    rgba = mcolors.to_rgba_array([css4, xkcd])
    luma = 0.299 * rgba[:, 0] + 0.587 * rgba[:, 1] + 0.114 * rgba[:, 2]
    css4_text_color = 'k' if luma[0] > 0.5 else 'w'
    xkcd_text_color = 'k' if luma[1] > 0.5 else 'w'

    col_shift = (j // n_rows) * 3
    y_pos = j % n_rows
    text_args = dict(fontsize=10, weight='bold' if css4 == xkcd else None)
    ax.add_patch(mpatch.Rectangle((0 + col_shift, y_pos), 1, 1, color=css4))
    ax.add_patch(mpatch.Rectangle((1 + col_shift, y_pos), 1, 1, color=xkcd))
    ax.text(0.5 + col_shift, y_pos + .7, css4,
            color=css4_text_color, ha='center', **text_args)
    ax.text(1.5 + col_shift, y_pos + .7, xkcd,
            color=xkcd_text_color, ha='center', **text_args)
    ax.text(2 + col_shift, y_pos + .7, f'  {color_name}', **text_args)

for g in range(n_groups):
    ax.hlines(range(n_rows), 3*g, 3*g + 2.8, color='0.7', linewidth=1)
    ax.text(0.5 + 3*g, -0.3, 'X11/CSS4', ha='center')
    ax.text(1.5 + 3*g, -0.3, 'xkcd', ha='center')

ax.set_xlim(0, 3 * n_groups)
ax.set_ylim(n_rows, -1)
ax.axis('off')

plt.show()
3.

So sánh giữa các màu X11/CSS4 và XKCD#

Màu sắc XKCD đến từ một cuộc khảo sát người dùng được thực hiện bởi XKCD Webcomic.

95 trong số các tên màu 148 X11/CSS4 cũng xuất hiện trong Khảo sát màu XKCD. Hầu như tất cả chúng đều ánh xạ tới các giá trị màu khác nhau trong X11/CSS4 và trong bảng màu XKCD. Chỉ có 'đen', 'trắng' và 'cyan' là giống hệt nhau.

Ví dụ,

import matplotlib.colors as mcolors
import matplotlib.patches as mpatch

overlap = {name for name in mcolors.CSS4_COLORS
           if f'xkcd:{name}' in mcolors.XKCD_COLORS}

fig = plt.figure(figsize=[9, 5])
ax = fig.add_axes([0, 0, 1, 1])

n_groups = 3
n_rows = len(overlap) // n_groups + 1

for j, color_name in enumerate(sorted(overlap)):
    css4 = mcolors.CSS4_COLORS[color_name]
    xkcd = mcolors.XKCD_COLORS[f'xkcd:{color_name}'].upper()

    # Pick text colour based on perceived luminance.
    rgba = mcolors.to_rgba_array([css4, xkcd])
    luma = 0.299 * rgba[:, 0] + 0.587 * rgba[:, 1] + 0.114 * rgba[:, 2]
    css4_text_color = 'k' if luma[0] > 0.5 else 'w'
    xkcd_text_color = 'k' if luma[1] > 0.5 else 'w'

    col_shift = (j // n_rows) * 3
    y_pos = j % n_rows
    text_args = dict(fontsize=10, weight='bold' if css4 == xkcd else None)
    ax.add_patch(mpatch.Rectangle((0 + col_shift, y_pos), 1, 1, color=css4))
    ax.add_patch(mpatch.Rectangle((1 + col_shift, y_pos), 1, 1, color=xkcd))
    ax.text(0.5 + col_shift, y_pos + .7, css4,
            color=css4_text_color, ha='center', **text_args)
    ax.text(1.5 + col_shift, y_pos + .7, xkcd,
            color=xkcd_text_color, ha='center', **text_args)
    ax.text(2 + col_shift, y_pos + .7, f'  {color_name}', **text_args)

for g in range(n_groups):
    ax.hlines(range(n_rows), 3*g, 3*g + 2.8, color='0.7', linewidth=1)
    ax.text(0.5 + 3*g, -0.3, 'X11/CSS4', ha='center')
    ax.text(1.5 + 3*g, -0.3, 'xkcd', ha='center')

ax.set_xlim(0, 3 * n_groups)
ax.set_ylim(n_rows, -1)
ax.axis('off')

plt.show()
4 bản đồ đến
import matplotlib.colors as mcolors
import matplotlib.patches as mpatch

overlap = {name for name in mcolors.CSS4_COLORS
           if f'xkcd:{name}' in mcolors.XKCD_COLORS}

fig = plt.figure(figsize=[9, 5])
ax = fig.add_axes([0, 0, 1, 1])

n_groups = 3
n_rows = len(overlap) // n_groups + 1

for j, color_name in enumerate(sorted(overlap)):
    css4 = mcolors.CSS4_COLORS[color_name]
    xkcd = mcolors.XKCD_COLORS[f'xkcd:{color_name}'].upper()

    # Pick text colour based on perceived luminance.
    rgba = mcolors.to_rgba_array([css4, xkcd])
    luma = 0.299 * rgba[:, 0] + 0.587 * rgba[:, 1] + 0.114 * rgba[:, 2]
    css4_text_color = 'k' if luma[0] > 0.5 else 'w'
    xkcd_text_color = 'k' if luma[1] > 0.5 else 'w'

    col_shift = (j // n_rows) * 3
    y_pos = j % n_rows
    text_args = dict(fontsize=10, weight='bold' if css4 == xkcd else None)
    ax.add_patch(mpatch.Rectangle((0 + col_shift, y_pos), 1, 1, color=css4))
    ax.add_patch(mpatch.Rectangle((1 + col_shift, y_pos), 1, 1, color=xkcd))
    ax.text(0.5 + col_shift, y_pos + .7, css4,
            color=css4_text_color, ha='center', **text_args)
    ax.text(1.5 + col_shift, y_pos + .7, xkcd,
            color=xkcd_text_color, ha='center', **text_args)
    ax.text(2 + col_shift, y_pos + .7, f'  {color_name}', **text_args)

for g in range(n_groups):
    ax.hlines(range(n_rows), 3*g, 3*g + 2.8, color='0.7', linewidth=1)
    ax.text(0.5 + 3*g, -0.3, 'X11/CSS4', ha='center')
    ax.text(1.5 + 3*g, -0.3, 'xkcd', ha='center')

ax.set_xlim(0, 3 * n_groups)
ax.set_ylim(n_rows, -1)
ax.axis('off')

plt.show()
5 trong khi
import matplotlib.colors as mcolors
import matplotlib.patches as mpatch

overlap = {name for name in mcolors.CSS4_COLORS
           if f'xkcd:{name}' in mcolors.XKCD_COLORS}

fig = plt.figure(figsize=[9, 5])
ax = fig.add_axes([0, 0, 1, 1])

n_groups = 3
n_rows = len(overlap) // n_groups + 1

for j, color_name in enumerate(sorted(overlap)):
    css4 = mcolors.CSS4_COLORS[color_name]
    xkcd = mcolors.XKCD_COLORS[f'xkcd:{color_name}'].upper()

    # Pick text colour based on perceived luminance.
    rgba = mcolors.to_rgba_array([css4, xkcd])
    luma = 0.299 * rgba[:, 0] + 0.587 * rgba[:, 1] + 0.114 * rgba[:, 2]
    css4_text_color = 'k' if luma[0] > 0.5 else 'w'
    xkcd_text_color = 'k' if luma[1] > 0.5 else 'w'

    col_shift = (j // n_rows) * 3
    y_pos = j % n_rows
    text_args = dict(fontsize=10, weight='bold' if css4 == xkcd else None)
    ax.add_patch(mpatch.Rectangle((0 + col_shift, y_pos), 1, 1, color=css4))
    ax.add_patch(mpatch.Rectangle((1 + col_shift, y_pos), 1, 1, color=xkcd))
    ax.text(0.5 + col_shift, y_pos + .7, css4,
            color=css4_text_color, ha='center', **text_args)
    ax.text(1.5 + col_shift, y_pos + .7, xkcd,
            color=xkcd_text_color, ha='center', **text_args)
    ax.text(2 + col_shift, y_pos + .7, f'  {color_name}', **text_args)

for g in range(n_groups):
    ax.hlines(range(n_rows), 3*g, 3*g + 2.8, color='0.7', linewidth=1)
    ax.text(0.5 + 3*g, -0.3, 'X11/CSS4', ha='center')
    ax.text(1.5 + 3*g, -0.3, 'xkcd', ha='center')

ax.set_xlim(0, 3 * n_groups)
ax.set_ylim(n_rows, -1)
ax.axis('off')

plt.show()
6 bản đồ đến
import matplotlib.colors as mcolors
import matplotlib.patches as mpatch

overlap = {name for name in mcolors.CSS4_COLORS
           if f'xkcd:{name}' in mcolors.XKCD_COLORS}

fig = plt.figure(figsize=[9, 5])
ax = fig.add_axes([0, 0, 1, 1])

n_groups = 3
n_rows = len(overlap) // n_groups + 1

for j, color_name in enumerate(sorted(overlap)):
    css4 = mcolors.CSS4_COLORS[color_name]
    xkcd = mcolors.XKCD_COLORS[f'xkcd:{color_name}'].upper()

    # Pick text colour based on perceived luminance.
    rgba = mcolors.to_rgba_array([css4, xkcd])
    luma = 0.299 * rgba[:, 0] + 0.587 * rgba[:, 1] + 0.114 * rgba[:, 2]
    css4_text_color = 'k' if luma[0] > 0.5 else 'w'
    xkcd_text_color = 'k' if luma[1] > 0.5 else 'w'

    col_shift = (j // n_rows) * 3
    y_pos = j % n_rows
    text_args = dict(fontsize=10, weight='bold' if css4 == xkcd else None)
    ax.add_patch(mpatch.Rectangle((0 + col_shift, y_pos), 1, 1, color=css4))
    ax.add_patch(mpatch.Rectangle((1 + col_shift, y_pos), 1, 1, color=xkcd))
    ax.text(0.5 + col_shift, y_pos + .7, css4,
            color=css4_text_color, ha='center', **text_args)
    ax.text(1.5 + col_shift, y_pos + .7, xkcd,
            color=xkcd_text_color, ha='center', **text_args)
    ax.text(2 + col_shift, y_pos + .7, f'  {color_name}', **text_args)

for g in range(n_groups):
    ax.hlines(range(n_rows), 3*g, 3*g + 2.8, color='0.7', linewidth=1)
    ax.text(0.5 + 3*g, -0.3, 'X11/CSS4', ha='center')
    ax.text(1.5 + 3*g, -0.3, 'xkcd', ha='center')

ax.set_xlim(0, 3 * n_groups)
ax.set_ylim(n_rows, -1)
ax.axis('off')

plt.show()
7. Do những vụ va chạm tên này, tất cả các màu XKCD đều có tiền tố
>>> a = Color(0x93, 0x03, 0xAA) # set using hex
>>> print a
#9303AA
>>> b = Color(12, 123, 3) # set using int
>>> print b
#0C7B03
8.

Hình ảnh dưới đây cho thấy các vụ va chạm tên. Tên màu nơi các giá trị màu đồng ý in đậm.

import matplotlib.colors as mcolors
import matplotlib.patches as mpatch

overlap = {name for name in mcolors.CSS4_COLORS
           if f'xkcd:{name}' in mcolors.XKCD_COLORS}

fig = plt.figure(figsize=[9, 5])
ax = fig.add_axes([0, 0, 1, 1])

n_groups = 3
n_rows = len(overlap) // n_groups + 1

for j, color_name in enumerate(sorted(overlap)):
    css4 = mcolors.CSS4_COLORS[color_name]
    xkcd = mcolors.XKCD_COLORS[f'xkcd:{color_name}'].upper()

    # Pick text colour based on perceived luminance.
    rgba = mcolors.to_rgba_array([css4, xkcd])
    luma = 0.299 * rgba[:, 0] + 0.587 * rgba[:, 1] + 0.114 * rgba[:, 2]
    css4_text_color = 'k' if luma[0] > 0.5 else 'w'
    xkcd_text_color = 'k' if luma[1] > 0.5 else 'w'

    col_shift = (j // n_rows) * 3
    y_pos = j % n_rows
    text_args = dict(fontsize=10, weight='bold' if css4 == xkcd else None)
    ax.add_patch(mpatch.Rectangle((0 + col_shift, y_pos), 1, 1, color=css4))
    ax.add_patch(mpatch.Rectangle((1 + col_shift, y_pos), 1, 1, color=xkcd))
    ax.text(0.5 + col_shift, y_pos + .7, css4,
            color=css4_text_color, ha='center', **text_args)
    ax.text(1.5 + col_shift, y_pos + .7, xkcd,
            color=xkcd_text_color, ha='center', **text_args)
    ax.text(2 + col_shift, y_pos + .7, f'  {color_name}', **text_args)

for g in range(n_groups):
    ax.hlines(range(n_rows), 3*g, 3*g + 2.8, color='0.7', linewidth=1)
    ax.text(0.5 + 3*g, -0.3, 'X11/CSS4', ha='center')
    ax.text(1.5 + 3*g, -0.3, 'xkcd', ha='center')

ax.set_xlim(0, 3 * n_groups)
ax.set_ylim(n_rows, -1)
ax.axis('off')

plt.show()

Hướng dẫn how to define colors in python - cách xác định màu sắc trong python

Tổng thời gian chạy của tập lệnh: (0 phút 1.410 giây) ( 0 minutes 1.410 seconds)

Phòng trưng bày được tạo ra bởi Sphinx-Gallery

Mã cho màu trong Python là gì?

Định dạng là;\ 033 [= mã thoát, điều này luôn giống nhau.1 = phong cách, 1 cho bình thường.32 = Màu văn bản, 32 cho màu xanh lá cây tươi sáng.

Có chức năng màu trong Python không?

Hàm Wand Color () trong hàm Python Color () vẽ một màu trên hình ảnh bằng màu điền hiện tại, bắt đầu ở vị trí & phương thức được chỉ định.Sử dụng cùng một đối số làm phương thức color (). in Python color() function draws a color on the image using current fill color, starting at specified position & method. Uses same arguments as color() method.