【Python】matplotlibで黒背景のグラフを描画する

matplotlibでは様々なグラフを描画できますが、白背景のグラフが常識になっている方も多いのではないでしょうか。

今回はmatplitlibで黒背景のグラフを描画する方法を紹介します。今回はplt.style.use()を使った方法を紹介します。

普通にグラフを描画した場合

まずはいつも通りグラフを描いてみます。かっこいいグラフがmatplotlib公式にあったので、拾ってきました。

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

L = 6
x = np.linspace(0, L)
ncolors = len(plt.rcParams['axes.prop_cycle'])
shift = np.linspace(0, L, ncolors, endpoint=False)
for s in shift:
    ax.plot(x, np.sin(x + s), 'o-')
ax.set_xlabel('x-axis')
ax.set_ylabel('y-axis')

plt.show()
plt.style.use('default')

黒背景のグラフを描画する

では、上記のグラフを黒背景にしていきます。背景色の変更はplt.style.use()を使います。スタイルは数種類用意されていますが、黒背景の場合は’dark_background’を指定します。

import numpy as np
import matplotlib.pyplot as plt

plt.style.use('dark_background')

fig, ax = plt.subplots()

L = 6
x = np.linspace(0, L)
ncolors = len(plt.rcParams['axes.prop_cycle'])
shift = np.linspace(0, L, ncolors, endpoint=False)
for s in shift:
    ax.plot(x, np.sin(x + s), 'o-')
ax.set_xlabel('x-axis')
ax.set_ylabel('y-axis')

plt.show()
plt.style.use('dark_background')

カラフルなグラフが非常にバエますね。黒背景への変更は非常に簡単ですね。

【おまけ】他のスタイルも試してみる

他にもいくつかスタイルがあるので、試してみます。

plt.style.use(‘classic’)

plt.style.use('classic')

plt.style.use(‘Solarize_Light2’)

plt.style.use('Solarize_Light2')

plt.style.use(‘grayscale’)

plt.style.use('grayscale')

まとめ

matplitlibで黒背景のグラフを描画する方法を紹介しました。方法としては非常に簡単でした。また、plt.style.use()には他にもスタイルが用意されているので、機会があればぜひ使ってみてください。

ではでは👋