[英]Is there a context manager for temporarily changing matplotlib settings?
[英]How to change matplotlib settings temporarily?
我通常在绘制任何设置fontsize, figuresize
大小、图形大小和其他设置以更好地满足我的需要之前设置rcParams
。 但是对于某些axes
或figure
,我想更改某些设置。 例如,假设我在默认值中设置了 fontsize = 20,并且对于我添加到轴的插图,我想将所有字体大小更改为 12。实现它的最简单方法是什么? 目前我正在手动调整不同文本的字体大小,即 label 字体大小,勾选 label 字体大小等! 是否可以做类似的事情
Some plotting here with fontsize=20
with fontsize=12 :
inset.plot(x,y)
Set various labels and stuff
Resume plotting with fontsize=20
Matplotlib 为 rc 参数rc_context()
提供了一个上下文管理器。 例如
from matplotlib import pyplot as plt
rc1 = {"font.size" : 16}
rc2 = {"font.size" : 8}
plt.rcParams.update(rc1)
fig, ax = plt.subplots()
with plt.rc_context(rc2):
axins = ax.inset_axes([0.6, 0.6, 0.37, 0.37])
plt.show()
我不确定是否可以临时更改设置,但您可以更改单个 plot 的设置,然后将它们更改回默认值:
import matplotlib as mpl
mpl.rcParams.update(mpl.rcParamsDefault)
或者,如果您想对多个绘图使用相同的设置,您可以定义一个 function 将它们更改为您的特定配置,然后将它们改回:
def fancy_plot(ax, tick_formatter=mpl.ticker.ScalarFormatter()):
"""
Some function to store your unique configuration
"""
mpl.rcParams['figure.figsize'] = (16.0, 12.0)
mpl.style.use('ggplot')
mpl.rcParams.update({'font.size': fontsize})
ax.spines['bottom'].set_color('black')
ax.spines['top'].set_color('black')
ax.spines['right'].set_color('black')
ax.spines['left'].set_color('black')
ax.set_facecolor((1,1,1))
ax.yaxis.set_major_formatter(tick_formatter)
ax.xaxis.set_major_formatter(tick_formatter)
def mpl_default():
"""
Some function to srestore default values
"""
mpl.rcParams.update(mpl.rcParamsDefault)
plt.style.use('default')
fig, ax = plt.subplots()
fancy_plot(ax)
fig.plot(x,y)
fig.show()
mpl_default()
fig, ax = plt.subplots()
fig.plot(some_other_x,some_other_y)
fig.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.