どうも、ちょげ(@chogetarou)です。
matplotlibでグラフの背景色を変える方法を紹介します。
方法

matplotlibでグラフの背景色を変える方法は、2つあります。
プロットエリアの背景色
1つは、プロットエリアの背景色を変える方法です。
まず、グラフを描画する前に、pyplotからaxes()を呼び出します。
pyplot.axes()の戻り値からset_facecolor()を呼び出します。
そして、set_facecolor()の引数に背景色を指定します。
import matplotlib.pyplot as plt
ax = plt.axes()
ax.set_facecolor(background_color)
上記の処理で、set_facecolor()の引数に指定した色が、グラフのプロットエリアの背景色になります。
使用例
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6]
y = [10, 4, 6, 19, 15, 7]
ax = plt.axes()
ax.set_facecolor('yellow')
plt.plot(x, y)
plt.show()

グラフエリアの背景色
もう1つは、グラフエリアの背景色を変える方法です。
まず、グラフを描画する前に、pyplotからfigure()を呼び出します。
そして、figure()の引数「facecolor」にグラフエリアの背景色を指定します。
import matplotlib.pyplot as plt
plt.figure(facecolor=background_color)
pyplot.figure()の引数に指定した色が、グラフのグラフエリアの背景色になります。
使用例
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6]
y = [10, 4, 6, 19, 15, 7]
plt.figure(facecolor='r')
plt.plot(x, y)
plt.show()

まとめ
グラフの背景色を変える方法は、次の2つです。
- プロットエリアの背景色を変える方法
ax = plt.axes()
ax.set_facecolor(background_color)
- グラフエリアの背景色を変える方法
plt.figure(facecolor=background_color)
コメント