Matplotlib入门[02]——style配置pyplot风格

Matplotlib入门[02]——style配置pyplot风格

参考:

  • https://ailearning.apachecn.org/
  • Matplotlib官网

使用Jupyter进行练习

Matplotlib入门[02]——style配置pyplot风格_第1张图片

import matplotlib.pyplot as plt
import numpy as np

stylepyplot 的一个子模块,方便进行风格转换, pyplot 有很多的预设风格,可以使用 plt.style.available 来查看:

plt.style.available
['Solarize_Light2',
 '_classic_test_patch',
 'bmh',
 'classic',
 'dark_background',
 'fast',
 'fivethirtyeight',
 'ggplot',
 'grayscale',
 'seaborn',
 'seaborn-bright',
 'seaborn-colorblind',
 'seaborn-dark',
 'seaborn-dark-palette',
 'seaborn-darkgrid',
 'seaborn-deep',
 'seaborn-muted',
 'seaborn-notebook',
 'seaborn-paper',
 'seaborn-pastel',
 'seaborn-poster',
 'seaborn-talk',
 'seaborn-ticks',
 'seaborn-white',
 'seaborn-whitegrid',
 'tableau-colorblind10']

默认风格

x = np.linspace(0, 2 * np.pi)
y = np.sin(x)

plt.plot(x, y)

plt.show()

Matplotlib入门[02]——style配置pyplot风格_第2张图片

例如,模仿 R 语言中常用的 ggplot 风格:

plt.style.use('ggplot')

plt.plot(x, y)

plt.show()

Matplotlib入门[02]——style配置pyplot风格_第3张图片

使用 context 将风格改变限制在某一个代码块内:

plt.figure()
with plt.style.context(('dark_background')):
    plt.subplot(211)
    plt.plot(x, y, 'r-o')
    plt.show()
# 在代码块外绘图则仍然是全局的风格。
plt.subplot(212)
plt.plot(x, y, 'r-o')
plt.show()

Matplotlib入门[02]——style配置pyplot风格_第4张图片Matplotlib入门[02]——style配置pyplot风格_第5张图片

还可以混搭使用多种风格,不过最右边的一种风格会将最左边的覆盖:

plt.style.use(['dark_background', 'ggplot'])

plt.plot(x, y, 'r-o')
plt.show()

Matplotlib入门[02]——style配置pyplot风格_第6张图片

你可能感兴趣的:(python机器学习,matplotlib,python,开发语言)