Matplotlib でプロットの背景色を設定する方法
Jinku Hu
2023年1月30日
2020年4月1日
Matplotlib
Matplotlib Color
Matplotlib rcParams

axes
オブジェクトの set_facecolor(color)
は背景、つまり対応するプロットの面の色を設定します。
特定のプロットの背景色を設定する
set_facecolor()
メソッドを呼び出す前に、axes
オブジェクトを取得する必要があります。
1. Matplotlib の Matlab に似たステートフル API
plt.plot(x, y)
ax = plt.gca()
完全なサンプルコード:
import matplotlib.pyplot as plt
plt.plot(range(5), range(5, 10))
ax = plt.gca()
ax.set_facecolor('m')
plt.show()
2.オブジェクト指向の方法で図と軸を作成する
figure
と axes
オブジェクトは一緒に作成できます。
fig, ax = plt.subplots()
または、最初に図
を作成し、次に axis
を開始します。
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
完全なサンプルコード:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1)
ax.plot(range(5), range(5, 10))
ax.set_facecolor('m')
plt.show()
または、
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(range(5), range(5, 10))
ax.set_facecolor('m')
plt.show()
Matplotlib で複数のプロットのデフォルトのプロット背景色を設定する
複数のプロットにデフォルトの背景色を設定する必要がある場合、rcParams
オブジェクトの axes.facecolor
プロパティを設定できます。
plt.rcParams['axes.facecolor'] = color
完全なサンプルコード:
import matplotlib.pyplot as plt
plt.rcParams['axes.facecolor'] = 'm'
plt.subplot(1,2, 1)
plt.plot(range(5), range(5, 10))
plt.subplot(1,2, 2)
plt.plot(range(5), range(10, 5, -1))
plt.show()
ご覧のとおり、2つのプロットの背景色は同じです。
Author: Jinku Hu
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn