我想编写一个模块,该模块具有从 matplotlibrc
文件中设置默认样式参数的功能。模块 style.py
的最小示例:
import matplotlib as mpl
def set_default():
mpl.rc_file('./matplotlibrc')
如果我想在带有内联绘图的 jupyter notebook 中使用该模块,当我在之前绘制任何内容之前调用 style.set_default()
时,不会显示内联绘图。
所以如果我打电话
%matplotlib inline
style.set_default()
plt.plot()
输出是一个空列表,没有显示任何图。如果我调用例如
plt.plot()
在启用内联绘图之后和调用 set_default
函数之前,两个 plot
调用的输出都是内联显示的。
这甚至会发生,当 matplotlibrc
文件为空时,就像在我的最小示例中一样。
有没有人知道为什么会发生这种情况并知道如何解决这个问题或如何使用 matplotlibrc
文件在模块中设置默认样式?
这也是 jupyter notebook 中两种情况的两张图片:
附加问题:当加载的 matplotlibrc
为空时,为什么第二种情况下的第二个图更大?
最佳答案
简短版本:使用 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')
当使用它时,它不会覆盖正在使用的后端,而只会更新那些在文件本身中指定的参数。
关于python - 从 matplotlibrc 文件加载 matplotlib rcparams 时,Jupyter notebook 内联绘图中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48320804/