matplotlibで線や点の色を薄くする

matplotlibで点や線の色を指定するとき、補助的な部分を使っている色よりも薄くしたいときに使います。こちらの記事で用いています。

matplotlibのデフォルトの色

デフォルトの色は"tab:blue""tab:orange"などで取得できます。色の名前からRGB値への変換はmatplotlib.colorsto_rgb関数でできます。色を薄くしたいとき、RGBにアルファチャンネルを追加します。タプルにアルファの値をくっつけて、そのままプロットすることができます(コード参照)。次の画像にコード実行例を示します。左上のプロットは普通に、右上のプロットは色を名前で指定、左下のプロットは色をRGBで指定、右下のプロットはアルファチャンネルを追加し薄くしたものです。

4種のプロット、左上は普通に、右上は色を名前で指定、左下は色をRGBで指定、右下はアルファチャンネルを追加し薄くした

アルファの値は0から1の範囲で、0にすればするほど透明になります。下の図はアルファの値を左から0, 0.1, 0.2, ...と変化させたものです。

左からアルファを徐々に増加させていくプロット

コード

コードの例はscatterですが、plotも同じようにできます。

import matplotlib.pyplot as plt
import matplotlib.colors as mcolors

# 普通にプロット
plt.subplot(2, 2, 1)
plt.scatter(1, 1)
plt.scatter(2, 1)
plt.scatter(3, 1)

# 色を名前で指定
plt.subplot(2, 2, 2)
plt.scatter(1, 1, c="tab:blue")
plt.scatter(2, 1, c="tab:orange")
plt.scatter(3, 1, c="tab:green")

# 色をRGB値で指定
blue_rgb = mcolors.to_rgb("tab:blue")
orange_rgb = mcolors.to_rgb("tab:orange")
green_rgb = mcolors.to_rgb("tab:green")
print(blue_rgb)
print(orange_rgb)
print(green_rgb)
plt.subplot(2, 2, 3)
plt.scatter(1, 1, c=(blue_rgb,))
plt.scatter(2, 1, c=(orange_rgb,))
plt.scatter(3, 1, c=(green_rgb,))

# 色をRGBA値で指定
blue_rgba = blue_rgb + (0.3,)
orange_rgba = orange_rgb + (0.3,)
green_rgba = green_rgb + (0.3,)
plt.subplot(2, 2, 4)
plt.scatter(1, 1, c=(blue_rgba,))
plt.scatter(2, 1, c=(orange_rgba,))
plt.scatter(3, 1, c=(green_rgba,))

plt.show()

for i in range(10):
    plt.scatter(i, 1, c=(blue_rgb + (i * 0.1,),))

plt.show()

蛇足

こんな警告についてです。

'c' argument looks like a single numeric RGB or RGBA sequence, which should be avoided as value-mapping will have precedence in case its length matches with 'x' & 'y'.  Please use a 2-D array with a single row if you really want to specify the same RGB or RGBA value for all points.

普通にRGBを指定してplt.scatterしようとすると上記警告が出ます。

import matplotlib.pyplot as plt
plt.scatter(1, 1, c=(1, 0, 0))
plt.show()

警告文に書いてあるように二次元化してあげると警告はなくなります。本来plt.scatterは複数の点を一気に描画するもので、色もいっぺんに入力するのが普通の使い方みたいです。もちろん、点数が多くなった時、一点ずつ描画するよりも一気に描画するほうが処理速度が速いです。

import matplotlib.pyplot as plt

# 同じ色で2点描画
plt.subplot(2, 1, 1)
plt.scatter((1, 2), (1, 1), c=((1, 0, 0),))

# 違う色で2点描画
plt.subplot(2, 1, 2)
plt.scatter((1, 2), (1, 1), c=((1, 0, 0), (0, 0, 1)))
plt.show()

コメント

タイトルとURLをコピーしました