グラフの背景色を変更してみる【matplotlib】

matplotlib

背景色と言っても主に以下の箇所に分かれると思います。

  • Figure
  • Axes
  • 凡例(legend)

それぞれ次のようにして背景色を変えることが可能です。

  • Figure –fig.set_facecolor(色)
  • Axes – ax.set_facecolor(色)
  • 凡例 – plt.legend(facecolor = 色)

背景を透過させたければRGBAなどでアルファチャンネルも設定すれば良いでしょう。
power pointの資料を作る時などに意外とアルファチャンネルも使ったりします。

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0, 5, 0.01)
sin = np.sin(x)
cos = np.cos(x)

fig, ax = plt.subplots()
fig.set_facecolor((0.8, 0.4, 0.4, 0.5))
ax.set_facecolor((0.7, 0.9, 0.8, 0.5))

plt.plot(x, sin, label='sin')
plt.plot(x, cos, label='cos')
plt.xlabel('x')
plt.ylabel('y')
plt.title('sin and cos')
plt.legend(facecolor='gray')
plt.show()

色の指定方法はこちらの記事をご覧ください。

こちらのドキュメントを参考にしました。

matplotlib.axes.Axes.set_facecolor — Matplotlib 3.6.3 documentation

コメント