4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

pip install colourで色の操作をする

Last updated at Posted at 2021-01-13

はじめに

plotlyやpyqtgraphはカラーパレット等が無い(or 少ない?)のでmatplotlibと比べて色を指定するのに苦労します。
今回は色のグラデーションなどを簡単に作成できるモジュールがあったので紹介します。

環境

Mac OS
Python 3.8.5
colour 0.1.5

pip install colour

詳細

作成

全て赤になります。

from colour import Color

Color('red')
Color(red=1)
Color('#f00')
Color('#ff0000')
Color(rgb=(1, 0, 0))  # 0~1
Color(hsl=(0, 1, 0.5))  # 0~1
Color(Color('red'))

値取得

from colour import Color

c = Color('red')  # <class 'colour.Color'>

cの値を取得します。

RGB

rgb = c.get_rgb()  # (1.0, 0.0, 0.0), tuple
rgb_hex = c.get_hex()  # #f00, str
rgb_hex_long = c.get_hex_l()  # #ff0000, str

HSL

hsl = c.get_hsl()  # hsl色空間 (0.0, 1.0, 0.5), tuple
hue = c.get_hue()  # 色相 0.0, float
saturation = c.get_saturation()  # 彩度 1.0, float
luminance = c.get_luminance()  # 輝度 0.5, float

単色

red = c.get_red()  # 1.0, float
blue = c.get_blue()  # 0.0, float
green = c.get_green()  # 0.0, float

値変更

c = Color('red')  # c = red

cの値を書き換えます

c.set_blue(1)  # c = magenta, set_red(), set_green()もある
c.set_saturation(0.5)  # 彩度の変更, c = #bf40bf, 0~1の間
c.set_luminance(0.2)  # 輝度の変更, c = #4c194c, 0~1の間
# 値が上書きされる
c.set_rgb((1, 0, 0))
c.set_hsl((0, 1, 0.5))

判定

Color('red') == Color('blue')
False
Color('red') == Color('red')
True
Color('red') != Color('blue')
True
Color('red') != Color('red')
False

グラデーション

始めの色と終わりの色, 分割数を指定します

# red - blue間
red = Color('red')
blue = Color('blue')
# 5分割 [<Color red>, <Color yellow>, <Color lime>, <Color cyan>, <Color blue>]
red_blue = list(red.range_to(blue, 5))

# black - white間
black = Color('black')
white = Color('white')
# 6分割 [<Color black>, <Color #333>, <Color #666>, <Color #999>, <Color #ccc>, <Color white>]
black_white = list(black.range_to(white, 6))

使用例

matplotlibやseabornは元々たくさん色が指定できるのであまり使わないかもしれません。
plotlyには結構使えると思います。

スクリーンショット 2021-01-13 22.01.20.png
from colour import Color
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

red = Color('red')
blue = Color('blue')
red_blue = list(red.range_to(blue, 100))

for num, color in enumerate(red_blue, 1):
    ax.plot([i for i in range(10)],
            [i * num for i in range(10)],
            c=color.get_hex_l())

plt.show()

参考

colour · PyPI

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?