用 Matplotlib 画图的时候经常会尝试多种不同配色,但是浏览到一个好看的配色时往往不方便应用到 Matplotlib 中,因为 Matplotlib 要求的颜色格式为:(R,G,B),其中 R,G,B 最大值为1。一般查到的配色方案都是以 RGB 最大值 255 来显示的。
使用以下代码可以选择将屏幕上任意一点,获取其满足 matplotlib 的 (R,G,B) 格式。
使用流程:
1.网页搜索科研配色,例如搜到如下配色:
2.运行下面的代码,把鼠标移到颜色块上,摁一下 Ctrl 取色 (可以取多次,直到退出取色),摁一下ESC,再摁一下 Ctrl 退出取色。
3.在控制台即可看到输出了:
4.把这些颜色复制到 Matplotlib 的画图函数中就行:
my_color = tuple(np.array([247, 241, 223])/255)
plt.plot(x, y, color=my_color)
附上获取屏幕颜色的代码:
import pyautogui
from ctypes import windll # 获取屏幕上某个坐标的颜色
from time import sleep
import keyboard
def get_color(x, y):
gdi32 = windll.gdi32
user32 = windll.user32
hdc = user32.GetDC(None) # 获取颜色值
pixel = gdi32.GetPixel(hdc, x, y) # 提取RGB值
r = pixel & 0x0000ff
g = (pixel & 0x00ff00) >> 8
b = pixel >> 16
return [r, g, b]
def run():
pyautogui.FAILSAFE = True# 鼠标移动左上角终止程序
pos = pyautogui.position()# 获取鼠标当前的位置
color = get_color(pos.x, pos.y) #获取指定位置的色值
if plt_mode == 1:
print('tuple(np.array('+'{}'.format(color)+')/255)')
else:
print('{}'.format(color))
return 0
def out():
global judge
judge = 0
# pyautogui.press('ctrl')
def clear():
pass
if __name__ == '__main__':
plt_mode = 1
judge = True
keyboard.add_hotkey('esc', out)
# recorded = keyboard.record(until='esc')
# keyboard._hotkeys = {}
while judge:
sleep(0.5)
keyboard.wait('ctrl')
if judge!=0:
run()
keyboard._hotkeys = {}