【matplotlib基础】--手绘风格

发布时间 2023-09-17 10:02:28作者: wang_yb

Matplotlib 中有一个很有趣的手绘风格。
如果不是特别严肃的分析报告,使用这个风格能给枯燥的数据分析图表带来一些活泼的感觉。

使用手绘风格非常简单,本篇主要手绘风格的效果以及如何配置中文的支持。

1. 中文支持

Matplotlib 的手绘风格默认是不支持中文的,中文在图形中会显示成方格子。
如果本机已经安装了中文字体,直接选择相应的字体即可,否则,需要下载安装。

1.1. 字体下载

如果没有合适的中文字体,可从下面地址下载:
https://url11.ctfile.com/f/45455611-872362386-3dafb6?p=6872 (访问密码: 6872)

这个zip包中有两个字体:

  1. 微软雅黑字体:中规中矩的中文字体
  2. 方正卡通字体:这个字体比较适合手绘风格,本篇的示例使用的就是这个字体。

1.2. 字体安装

如果是windows系统的话,字体下载后,直接双击,然后选择安装即可。
linux系统的话,一般是把字体文件复制到 /usr/share/fonts 目录下。

字体安装后,可能在 Matplotlib 中不会生效,这是因为Matplotlib 对字体有缓存。

windows中,删除缓存的字体文件(C:\Users\{登录系统的用户}\.matplotlib\fontlist-v330.json),重新运行程序,会再次生成字体缓存。

linux中,可以通过运行 fc-cache,重新生成字体缓存。

1.3. 显示效果

安装字体之后,改成手绘风格只需要添加一行代码:with plt.xkcd():

import numpy as np

import matplotlib
import matplotlib.pyplot as plt

#绘图示例图形的函数
def draw(title="中文标题"):
    #这里使用的是方正卡通字体
    plt.rcParams.update({
        "font.family": "FZKaTong-M19S",
        "font.size": 11
    })
    x = np.array(range(10))
    y = np.random.randint(10, 100, 10)

    fig = plt.figure(figsize=[8, 6])
    fig.subplots_adjust(hspace=0.5)
    fig.add_subplot(211)
    plt.plot(x, y, label="曲线1")
    y1 = np.random.randint(10, 100, 10)
    plt.plot(x, y1, label="曲线2")
    plt.legend()
    plt.title(title)

    fig.add_subplot(212)
    plt.bar(["苹果", "橘子", "香蕉", "西瓜", "桃子"],
            height=y[:5],
            color=["b", "c", "g", "m"])

#将绘制图形的函数放在 plt.xkcd上下文中即可
with plt.xkcd():
    draw()

image.png

中文用的是方正卡通字体,和手绘风格搭配较好。

2. 手绘风格参数

手绘风格函数 plt.xkcd()3个主要参数,调整这3个参数,可以修正手绘的效果。

3个参数分别是:

  1. scale:手绘的各种线条的弯曲程度
  2. length:每个弯曲处的长度
  3. randomness:产生弯曲的随机性

2.1. scale 参数

scale 越小,弯曲程度越低。

for scale in [0.5, 2, 10]:
    with plt.xkcd(scale=scale):
        draw()

image.png
image.png
image.png

2.2. length 参数

length 参数控制每个弯曲的长度,也就是 length越大,弯曲的越平滑。

for length in [1, 10, 100]:
    with plt.xkcd(length=length):
        draw(f"length 参数 = {length}")

image.png
image.png
image.png

2.3. randomness 参数

randomness 参数控制产生弯曲的随机性,randomness越大,产生的弯曲处越多。

for randomness in [1, 10, 100]:
    with plt.xkcd(randomness=randomness):
        draw(f"randomness 参数 = {randomness}")

image.png
image.png
image.png