设置全局参数——定制matplotlib(部分翻译)

本文介绍了如何使用matplotlib的style包切换绘图样式,包括预定义的样式、定义自定义样式、组合样式和临时样式。同时,文章详细讲解了rcParams模块,展示了如何动态更改matplotlib的默认设置,以及matplotlibrc文件的用法和配置位置。
摘要由CSDN通过智能技术生成

使用style包:

style包能让你很轻松的切花绘图的类型,预先在matplotlib中定义好了许多style类型供选择,使用的方式如下

import matplotlib.pyplot as plt
plt.style.use('ggplot')#ggplot就是一种style的名称

获得所有提供的styles的方法如下:

style_list = print(plt.style.available)

输出的所有类型如下(使用的时候可以如下选择):

['seaborn-paper',
 'seaborn-dark-palette',
 'seaborn-notebook',
 'dark_background',
 'seaborn-whitegrid',
 'seaborn-talk',
 'fivethirtyeight',
 'ggplot',
 'seaborn-ticks',
 'grayscale',
 'bmh',
 'seaborn-dark',
 'seaborn-poster',
 'seaborn-deep',
 'seaborn-darkgrid',
 'classic',
 'seaborn-white',
 'seaborn-colorblind',
 'seaborn-bright',
 'seaborn-pastel',
 'seaborn-muted']
定义属于自己的属性

你可以定义属于自己风格的style,具体的定义方式请查看源文档。

复合风格

plt.style.use(['bmh','dark_background'])
#plt.style.use(style)-->其中style类型有style : str, dict, or list
类型 介绍
str The name of a style or a path/URL to a style file. For a list of available style names, see style.available.
dict Dictionary with valid key/value pairs formatplotlib.rcParams.
list A list of style specifiers (str or dict) applied from first to last in the list.

暂时风格

不做介绍

rcParams模块(十分常用)

动态rc设定

我们可以动态的改变已经在style中预设好的rc参数,所有的rc设置都被存储在一个类似字典的变量中——matplotlib.rcParams,这是一个全局包,工作方式有如下几种:

#方式一
import matplotlib as mpl
mpl.rcParams['lines.linewidth'] = 2 #类字典格式,键值对
mpl.rcParams['lines.color'] = 'r'
#方式二
mpl.rc('lines',linewidth = 2,color = 'r')
#方式三
font = {
        'family' : 'monospace',
        'weight' : 'bold',
        'size'   : 'larger'
        }
mpl.rc('font',**font)

NOTICE:

#关于rc的解释
matplotlib.rc(group, **kwargs)
#即rc接受一个Group,这个Group就是类型,比如'font','lines','text'等等
#后面的可以直接接受单个的键值对,也可以直接接收字典

所有Group类型包含的属性见英文原文最后的matplotlibrc文档的示例


以下为原文:

Customizing matplotlib

Using style sheets

The style package adds support for easy-to-switch plotting “styles” with the same parameters as a matplotlibrc file (which is read at startup to configure matplotlib).

There are a number of pre-defined styles provided by matplotlib. For example, there’s a pre-defined style called “ggplot”, which emulates the aesthetics of ggplot (a popular plotting package for R). To use this style, just add:

>>> import matplotlib.pyplot as plt
>>> plt.style.use('ggplot')

To list all available styles, use:

>>> print(plt.style.available)

Defining your own style

You can create custom styles and use them by calling style.use with the path or URL to the style sheet. Additionally, if you add your <style-name>.mplstyle file to mpl_configdir/stylelib, you can reuse your custom style sheet with a call to style.use(<style-name>). By default mpl_configdir should be ~/.config/matplotlib, but you can check where yours is with matplotlib.get_configdir(); you may need to create this directory. You also can change the directory where matplotlib looks for the stylelib/ folder by setting the MPLCONFIGDIR environment variable, see matplotlib configuration and cache directory locations.

Note that a custom style sheet in mpl_configdir/stylelib will override a style sheet defined by matplotlib if the styles have the same name.

For example, you might want to create mpl_configdir/stylelib/presentation.mplstyle with the following:

axes.titlesize : 24
axes.labelsize : 20
lines.linewidth : 3
lines.markersize : 10
xtick.labelsize : 16
ytick.labelsize : 16

Then, when you want to adapt a plot designed for a paper to one that looks good in a presentation, you can just add:

>>> import matplotlib.pyplot as plt
>>> plt.style.use('presentation')

Composing styles

Style sheets are designed to be composed together. So you can have a style sheet that customizes colors and a separate style sheet that alters element sizes for presentations. These styles can easily be combined by passing a list of styles:

>>> import matplotlib.pyplot as plt
>>> plt.style.use(['dark_background', 'presentation'])

ote that styles further to the right will overwrite values that are already defined by styles on the left.

Temporary styling

If you only want to use a style for a specific block of code but don’t want to change the global styling, the style package provides a context manager for limiting your changes to a specific scope. To isolate your styling changes, you can write something like the following:

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>>
>>> with plt.style.context(('dark_background')):
>>>     plt.plot(np.sin(np.linspace(0, 2 * np.pi)), 'r-o')
>>>
>>> # Some plotting code with the default style
>>>
>>> plt.show()

matplotlib rcParams

Dynamic rc settings

You can also dynamically change the default rc settings in a python script or interactively from the python shell. All of the rc settings are stored in a dictionary-like variable called matplotlib.rcParams, which is global to the matplotlib package. rcParams can be modified directly, for example:

import matplotlib as mpl
mpl.rcParams['lines.linewidth'] = 2
mpl.rcParams['lines.color'] = 'r'

Matplotlib also provides a couple of convenience functions for modifying rc settings. The matplotlib.rc() command can be used to modify multiple settings in a single group at once, using keyword arguments:

import matplotlib as mpl
mpl.rc('lines', linewidth=2, color='r')

The matplotlib.rcdefaults() command will restore the standard matplotlib default settings.

There is some degree of validation when setting the values of rcParams, see matplotlib.rcsetup for details.

The matplotlibrc file

matplotlib uses matplotlibrc configuration files to customize all kinds of properties, which we call rc settings or rc parameters. You can control the defaults of almost every property in matplotlib: figure size and dpi, line width, color and style, axes, axis and grid properties, text and font properties and so on. matplotlib looks for matplotlibrc in four locations, in the following order:

  1. matplotlibrc in the current working directory, usually used for specific customizations that you do not want to apply elsewhere.

  2. $MATPLOTLIBRC/matplotlibrc.

  3. It next looks in a user-specific place, depending on your platform:

    • On Linux and FreeBSD, it looks in .config/matplotlib/matplotlibrc (or $XDG_CONFIG_HOME/matplotlib/matplotlibrc) if you’ve customized your environment.
    • On other platforms, it looks in .matplotlib/matplotlibrc.

    See matplotlib configuration and cache directory locations.

  4. *INSTALL*/matplotlib/mpl-data/matplotlibrc, where *INSTALL* is something like /usr/lib/python3.5/site-packages on Linux, and maybe C:\Python35\Lib\site-packages on Windows. Every time you install matplotlib, this file will be overwritten, so if you want your customizations to be saved, please move this file to your user-specific matplotlib directory.

To display where the currently active matplotlibrc file was loaded from, one can do

### 使用 Matplotlib 创建和操作画布 #### 导入库并配置环境 为了能够正常显示中文字符以及处理特殊符号,需要对 `matplotlib` 进行特定设置。这可以通过修改全局参数来实现: ```python import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False ``` 上述代码片段设置了字体为黑体 (`SimHei`) 并关闭了 Unicode 负号的支持[^4]。 #### 创建单个画布 使用 `plt.figure()` 函数可以创建一个新的画布,并可自定义其大小和其他属性。例如: ```python import numpy as np x = np.linspace(-1, 1, 20) y = 2 * x + 1 # 创建一个名为 "figure1" 的新画布,默认尺寸 plt.figure(num="figure1") plt.plot(x, y, linestyle=':', marker='o') # 创建另一个较大尺寸的新画布,命名为 "figure2" plt.figure(num="figure2", figsize=(8, 6)) plt.plot(x, x**2, ':', marker='o') plt.show() ``` 这段代码展示了如何创建不同名称和尺寸的两个独立画布,并分别在其上绘制简单的线形图。 #### 添加子图到现有画布 对于复杂的数据可视化需求,可能希望在同一张图表内展示多组不同的数据集。这时就可以利用 `subplot()` 或者 `subplots()` 来分割当前画布空间,从而容纳更多的视图组件。下面的例子说明了这两种方式的应用场景: ##### 方法一:使用 `plt.subplot()` 此函数接受三个整数作为输入——分别是行数、列数及要激活的具体位置编号(从左至右、由上而下计数)。比如: ```python for i in range(1, 5): plt.subplot(2, 2, i) # 定义了一个2×2布局下的第i个子区 plt.text(0.5, 0.5, str((2, 2, i)), ha='center') # 向每个子区内添加文本标签 plt.tight_layout() plt.show() ``` 这里通过循环迭代的方式快速构建出了四个带有文字标注的小窗口[^1]。 ##### 方法二:使用 `plt.subplots()` 相比之下,这种方法更加直观易懂,因为它直接返回了一对对象 `(fig, axes)` ,其中前者代表整个图形容器本身,后者则包含了所有已分配好的坐标系实例列表。因此非常适合于后续进一步定制化调整各个部分的行为特性: ```python fig, axs = plt.subplots(nrows=2, ncols=2) # 将二维数组展平以便更容易访问每一个单独元素 axs_flat = axs.flatten() for idx, ax in enumerate(axs_flat): ax.set_title(f'Subplot {idx}') plt.tight_layout() plt.show() ``` 此外还可以传递额外的关键字参数给 `subplots()` 来控制更多细节选项,像设定统一的主题风格或是启用极坐标模式等[^5]。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值