如何在Jupyter Notebook中永久修改matplotlib.rcParams默认值
Great question—having to re-set matplotlib rcParams every time you open Jupyter is such a hassle. Let's fix this for good with a few straightforward methods:
方法1:修改Matplotlib的全局配置文件(对所有用户/环境生效)
This method will apply your settings to every instance of matplotlib on your system, including Jupyter:
- First, find the path to the global config file. Run this in a Jupyter cell:
import matplotlib print(matplotlib.matplotlib_fname()) - Open the file with a text editor (you might need admin/sudo privileges for system-level paths).
- Locate the parameters you want to change, remove the
#comment, and replace the default value with your custom one. For example:# Original commented default # font.family: sans-serif # Modified to your preference font.family: 'Arial' figure.dpi: 120 axes.grid: True - Save the file, restart Jupyter Notebook, and your settings will take effect automatically.
方法2:创建用户专属配置文件(仅对你的账号生效,推荐)
If you don't want to mess with system-wide settings, this is the safer option:
- Find your user-specific config directory by running this in Jupyter:
The output will look likeimport matplotlib print(matplotlib.get_configdir())~/.config/matplotlib(Linux/macOS) orC:\Users\YourUsername\.matplotlib(Windows). - If there's no
matplotlibrcfile in this directory, create one. - Add your custom parameters to the file (same format as the global config):
# My personal matplotlib defaults font.family: 'Times New Roman' figure.dpi: 150 axes.facecolor: #f5f5f5 savefig.format: 'png' savefig.dpi: 300 - Save the file and restart Jupyter. These settings will load automatically and take priority over the global config.
方法3:仅在Jupyter中生效的启动脚本
If you want your settings to only apply to Jupyter (and not other Python environments using matplotlib):
- Find your Jupyter config directory by running this in a terminal/command prompt:
jupyter --config-dir - Create a
custom/startupfolder inside this directory if it doesn't exist. - Make a new
.pyfile in thestartupfolder (name it something like00-matplotlib-defaults.py—the00ensures it runs first):import matplotlib.pyplot as plt # Set your preferred rcParams here plt.rcParams['font.family'] = 'Arial' plt.rcParams['figure.dpi'] = 120 plt.rcParams['axes.grid'] = True plt.rcParams['axes.spines.right'] = False plt.rcParams['axes.spines.top'] = False - Save the file, restart Jupyter, and your settings will be applied every time you open a notebook.
Quick Tips
- You must restart Jupyter after modifying config files—refreshing the notebook page won't work.
- Priority order for settings: Jupyter startup script code > user-level
matplotlibrc> globalmatplotlibrc. - If you're unsure about a parameter name, run
print(plt.rcParams)in Jupyter to see all available configs and their current values.
内容的提问来源于stack exchange,提问作者nonickname
相关产品推荐
相关产品推荐

