短版:使用mpl.style.use 而不是mpl.rc_file。
长版:
您可以打印出正在使用的后端以查看发生了什么。
import matplotlib as mpl
def set_default():
mpl.rc_file('matplotlibrc.txt') # this is an empty file
import matplotlib.pyplot as plt
print mpl.get_backend()
# This prints u'TkAgg' (in my case) the default backend in use
# due to my rc Params
%matplotlib inline
print mpl.get_backend()
# This prints "module://ipykernel.pylab.backend_inline", because inline has been set
set_default()
print mpl.get_backend()
# This prints "agg", because this is the default backend reset by setting the empty rc file
plt.plot()
# Here, no plot is shown because agg (a non interactive backend) is used.
直到这里没有惊喜。
现在是第二种情况。
import matplotlib as mpl
def set_default():
mpl.rc_file('matplotlibrc.txt') # this is an empty file
import matplotlib.pyplot as plt
print mpl.get_backend()
# This prints u'TkAgg' (in my case) the default backend in use, same as above
%matplotlib inline
print mpl.get_backend()
# This prints "module://ipykernel.pylab.backend_inline", because inline has been set
plt.plot()
# This shows the inline plot, because the inline backend is active.
set_default()
print mpl.get_backend()
# This prints "agg", because this is the default backend reset by setting the new empty rc file
plt.plot()
# Here comes the supprise: Although "agg" is the backend, still, an inline plot is shown.
# This is due to the inline backend being the one registered in pyplot
# when doing the first plot. It cannot be changed afterwards.
重点是,您仍然可以更改后端,直到生成第一个图,而不是之后。
同样的论点也适用于图形大小。默认的 matplotlib 图形大小为(6.4,4.8),而使用内联后端设置的图形大小为(6.0,4.0)。图形 dpi 也不同,默认 rcParams 中为 100,而内联配置中为 72.。这使得情节显得更小。
现在到实际问题。我想这里使用样式表是为了为绘图设置一些样式,而不是更改后端。因此,您宁愿只从 rc 文件中设置样式。这可以以通常的方式完成,使用matplotlib.style.use
def set_default():
mpl.style.use('matplotlibrc.txt')
使用时,它不会覆盖正在使用的后端,而只会更新那些在文件本身中指定的参数。