Trong bài viết này, chúng ta sẽ học cách in văn bản có màu trong Python. Chúng tôi sẽ sử dụng một số mô-đun và thư viện tích hợp cũng như một số mã tùy chỉnh. Trước tiên chúng ta hãy xem nhanh cách Python đại diện cho mã màu Trong ngôn ngữ lập trình Python, văn bản có thể được thể hiện bằng các màu khác nhau. Có các thư viện Python rất đơn giản để sử dụng cho màu sắc và định dạng trong thiết bị đầu cuối. Lập trình viên nhận được phản hồi tốt hơn bằng cách in văn bản màu Hãy xem một số ví dụ hữu ích để tô màu văn bản trong Python In văn bản màu bằng Mô-đun coloramaChúng ta có thể sử dụng mô-đun colorama tích hợp sẵn của Python để in văn bản đầy màu sắc. Nó là một mô-đun in đa nền tảng. Trong phần này, văn bản màu có thể được thực hiện bằng cách sử dụng tốc ký hằng số Colorama’s cho chuỗi thoát ANSI . Chỉ cần nhập từ mô-đun coloroma và nhận đầu ra mong muốn của bạn import colorama
from colorama import Fore
print(Fore.RED + 'This text is red in color')
Văn bản này có màu đỏ
In văn bản màu bằng mô-đun termcolorChúng ta có thể sử dụng mô-đun termcolor tích hợp để in màu văn bản trong Python. Thuật ngữ màu là một mô-đun python để định dạng Màu ANSII cho đầu ra trong thiết bị đầu cuối. Đối với điều này, mô-đun sys phải được nhập trước và sau đó được tô màu từ mô-đun termcolor như bên dưới import sys
from termcolor import colored, cprint
text = colored('Hello, World!', 'red', attrs=['reverse', 'blink'])
print(text)
Chào thế giới
In văn bản màu bằng mã ANSI trong PythonChúng tôi có thể sử dụng kiểu mã ANSI để làm cho văn bản của bạn dễ đọc và sáng tạo hơn, bạn có thể sử dụng mã thoát ANSI để thay đổi màu của đầu ra văn bản trong chương trình python. Một trường hợp sử dụng tốt cho việc này là làm nổi bật các lỗi. Các mã thoát được nhập ngay vào câu lệnh in print("\033[1;32m This text is Bright Green \n")
Văn bản này có màu xanh sáng
Mã thoát ANSI ở trên sẽ đặt màu văn bản thành màu xanh lá cây tươi sáng. Định dạng là; - \033[ = Mã thoát, mã 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 sáng
In văn bản màu bằng mô-đun màuChúng ta có thể sử dụng mô-đun color và các chức năng của nó để tô màu văn bản trong Python. Nó là một thư viện có thể được sử dụng sau khi cài đặt bằng cách sử dụng lệnh pip. Vì vậy, trước tiên, hãy cài đặt nó và sau đó nhập nó vào tập lệnh python của bạn để làm nổi bật màu văn bản from colored import fg
print ('%s Hello World !!! %s' % (fg(1), attr(0)))
Chào thế giới
ví dụ 2Chúng ta cũng có thể chuyển tên của màu vào hàm fg(). Thấy chưa, nó in văn bản có màu xanh lam khi chúng tôi chuyển màu xanh lam làm giá trị from colored import fg
color = fg('blue')
print (color + 'Hello World !!!')
Chào thế giới
Đây là những cách khác nhau để bạn có thể in văn bản của mình bằng các màu khác nhau. Bạn cũng có thể thêm các kiểu khác nhau vào văn bản của mình, các màu nền khác nhau cho văn bản của bạn Phần kết luậnTrong bài viết này, chúng ta đã học cách tô màu văn bản và in màu nền bằng cách sử dụng một số chức năng tích hợp như mô-đun coloroma , mô-đun import sys
from termcolor import colored, cprint
text = colored('Hello, World!', 'red', attrs=['reverse', 'blink'])
print(text) 0, import sys
from termcolor import colored, cprint
text = colored('Hello, World!', 'red', attrs=['reverse', 'blink'])
print(text) 1, v.v. Chúng tôi cũng đã sử dụng một số mã tùy chỉnh. Ví dụ: chúng tôi đã sử dụng các màu và văn bản khác nhau để đánh dấu và in văn bản có màu Các màu lục lam, lục lam, đỏ tươi và vàng không trùng với màu X11/CSS4. Các sắc thái cụ thể của chúng được chọn để hiển thị rõ hơn các vạch màu trên nền điển hì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 như màu xanhimport 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 như màu xanh lá câyimport 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 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')
8 dưới dạng lục lamimport 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')
9 như màu đỏ tươiimport 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()
0 màu vàngimport 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()
1 màu đenimport 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()
2 màu trắng
Tên màu X11/CSS4 không phân biệt chữ hoa chữ thường và không có dấu cách 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()
3import 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
Tên màu không phân biệt chữ hoa chữ thường từ khảo sát màu xkcd với tiền tố 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()
5import 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()
6import 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
Màu Tableau không phân biệt chữ hoa chữ thường từ bảng phân loại 'T10' Ghi chú Đây là chu kỳ màu mặc định 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()
8import 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()
9(0.1, 0.2, 0.5) 0
(0.1, 0.2, 0.5) 1
(0.1, 0.2, 0.5) 2
(0.1, 0.2, 0.5) 3
(0.1, 0.2, 0.5) 4
(0.1, 0.2, 0.5) 5
(0.1, 0.2, 0.5) 6
(0.1, 0.2, 0.5) 7
Thông số màu "CN" trong đó (0.1, 0.2, 0.5) 8 đứng trước một số đóng vai trò là chỉ mục trong chu kỳ thuộc tính mặc định Ghi chú Matplotlib lập 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 (0.1, 0.2, 0.5) 9
(0.1, 0.2, 0.5, 0.3) 0
(0.1, 0.2, 0.5, 0.3) 1 (mặc định. (0.1, 0.2, 0.5, 0.3) 2)
Xem thêm Các liên kết sau đây cung cấp thêm thông tin về màu sắc trong Matplotlib"Đỏ", "Xanh lục" và "Xanh dương" là cường độ của các màu đó. Kết hợp lại, chúng đại diện cho không gian màu minh bạchGiá trị alpha của một màu xác định độ trong suốt của nó, trong đó 0 hoàn toàn trong suốt và 1 hoàn toàn mờ đục. Khi một màu ở trạng thái nửa trong suốt, màu nền sẽ hiển thị xuyên suốt Giá trị alpha xác định màu kết quả bằng cách trộn màu nền trước với màu nền theo công thức \[RGB_{kết quả} = RGB_{nền} * (1 - \alpha) + RGB_{nền trước} * \alpha\] Biểu đồ sau đây minh họa ảnh hưởng của tính minh bạch import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import numpy as np
fig, ax = plt.subplots(figsize=(6.5, 1.65), layout='constrained')
ax.add_patch(Rectangle((-0.2, -0.35), 11.2, 0.7, color='C1', alpha=0.8))
for i, alpha in enumerate(np.linspace(0, 1, 11)):
ax.add_patch(Rectangle((i, 0.05), 0.8, 0.6, alpha=alpha, zorder=0))
ax.text(i+0.4, 0.85, f"{alpha:.1f}", ha='center')
ax.add_patch(Rectangle((i, -0.05), 0.8, -0.6, alpha=alpha, zorder=2))
ax.set_xlim(-0.2, 13)
ax.set_ylim(-1, 1)
ax.set_title('alpha values')
ax.text(11.3, 0.6, 'zorder=1', va='center', color='C0')
ax.text(11.3, 0, 'zorder=2\nalpha=0.8', va='center', color='C1')
ax.text(11.3, -0.6, 'zorder=3', va='center', color='C0')
ax.axis('off')
Hình chữ nhật màu cam là bán trong suốt với alpha = 0. 8. Hàng trên cùng của hình vuông màu xanh lam được vẽ bên dưới và hàng dưới cùng của hình vuông màu xanh lam được vẽ ở trên cùng của hình chữ nhật màu cam Xem thêm Zorder Demo để tìm hiểu thêm về thứ tự bản vẽ. Lựa chọn màu "CN"Matplotlib chuyển đổi màu "CN" thành RGBA khi vẽ Nghệ sĩ. Phần Tạo kiểu với bộ tạo kiểu 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. 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 (0.1, 0.2, 0.5) 9 là tiêu đề. Mỗi ô sử dụng màu thứ hai và thứ ba của (0.1, 0.2, 0.5, 0.3) 1 của mỗi kiểu (mặc định. (0.1, 0.2, 0.5, 0.3) 2). Họ lần lượt là (0.1, 0.2, 0.5, 0.3) 0 và (0.1, 0.2, 0.5, 0.3) 8 So sánh giữa màu X11/CSS4 và xkcdMàu xkcd đến từ một cuộc khảo sát người dùng được thực hiện bởi webcomic xkcd 95 trong số 148 tên màu X11/CSS4 cũng xuất hiện trong khảo sát màu xkcd. Hầu như tất cả chúng ánh xạ tới các giá trị màu khác nhau trong X11/CSS4 và trong bảng xkcd. Chỉ có 'đen', 'trắng' và 'lục lam' là giống hệt nhau Ví dụ: (0.1, 0.2, 0.5, 0.3) 9 ánh xạ tới '#0f0f0f' 0 trong khi '#0f0f0f' 1 ánh xạ tới '#0f0f0f' 2. Do những xung đột tên này, tất cả các màu xkcd đều có tiền tố 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
Làm cách nào để cài đặt mô-đun màu trong Python?
Bạn sẽ phải tải xuống liên kết mô-đun và cài đặt nó. Khi bạn đã hoàn thành việc đó, hai dòng ở đầu mã của bạn sẽ giúp mã hoạt động, ngay cả trên Windows. nhập khẩu colorama colorama. . Cài đặt mô-đun termcolor. cài đặt thuật ngữ pip3 Nhập lớp màu từ termcolor. . Sử dụng các phương pháp được cung cấp, dưới đây là một ví dụ
Có thư viện màu nào trong Python không?
Color là một gói mã nguồn mở Python cung cấp một số lượng lớn các thuật toán và bộ dữ liệu cho khoa học màu sắc. Nó được cung cấp miễn phí theo các điều khoản của Giấy phép BSD Mới.
Làm cách nào để thay đổi màu sắc trong Python?
Nhấp chuột phải vào góc trên bên trái của cửa sổ bảng điều khiển Python và chọn Thuộc tính. Trong hộp thoại xuất hiện, hãy chọn tab có nhãn Màu sắc . Trên đó, bạn có thể đặt nền màn hình và màu văn bản.
Mã màu trong Python là gì?
Màu trăn . 'b'- màu xanh 'c' - lục lam 'g' - màu xanh lá cây 'k' - đen 'm' - đỏ tươi 'r' - đỏ 'w' - trắng 'y' - màu vàng |