讓數據動起來!用 Python 製作動畫可視化效果,讓數據不再枯燥!

通常大家做出來的圖表,絕大部分都是靜態的,有時會顯得不夠吸引人。

今天小 F 就給大家介紹一下,如何用 Python 繪製動態圖表。

主要是使用到 Matplotlib+imageio,其中 Matplotlib 就有一個 Animation 類,可以生成動圖 GIF,不過使用起來學習成本較高,還是有一定難度的。

這裏我將先創建靜態圖表的圖片,然後使用 Imageio 創建一個 GIF(動態圖表)。

一共給大家介紹三種動態圖表的繪製,折線圖,條形圖,散點圖。

01 折線圖

先來繪製一個簡單的折線圖看看。

import os
import numpy as np
import matplotlib.pyplot as plt
import imageio

# 生成40個取值在30-40的數
y = np.random.randint(30, 40, size=(40))
# 繪製折線
plt.plot(y)
# 設置y軸最小值和最大值
plt.ylim(20, 50)

# 顯示
plt.show()

使用 Numpy 創建一個數值範圍在 30 到 40 之間的隨機整數列表,結果如下。

下面將對整數列表進行切片,生成不同階段的圖表。

# 第一張圖
plt.plot(y[:-3])
plt.ylim(20, 50)
plt.savefig('1.png')
plt.show()

# 第二張圖
plt.plot(y[:-2])
plt.ylim(20, 50)
plt.savefig('2.png')
plt.show()

# 第三張圖
plt.plot(y[:-1])
plt.ylim(20, 50)
plt.savefig('3.png')
plt.show()

# 第四張圖
plt.plot(y)
plt.ylim(20, 50)
plt.savefig('4.png')
plt.show()

得到 x 軸爲 0:36、0:37、0:38、0:39 四個折線圖表。

有了這四張圖,我們就可以使用 Imageio 生成 GIF 了。

# 生成Gif
with imageio.get_writer('mygif.gif'mode='I') as writer:
    for filename in ['1.png''2.png''3.png''4.png']:
        image = imageio.imread(filename)
        writer.append_data(image)

動圖來了。

一個會動的折線圖表就製作出來了,不過不是從 x 軸座標爲 0 的時候開始的。

filenames = []
num = 0
for i in y:
    num += 1
    # 繪製40張折線圖
    plt.plot(y[:num])
    plt.ylim(20, 50)

    # 保存圖片文件
    filename = f'{num}.png'
    filenames.append(filename)
    plt.savefig(filename)
    plt.close()

# 生成gif
with imageio.get_writer('mygif.gif'mode='I') as writer:
    for filename in filenames:
        image = imageio.imread(filename)
        writer.append_data(image)

# 刪除40張折線圖
for filename in set(filenames):
    os.remove(filename)

繪製出 40 張折線圖,並且保存圖片,生成 GIF。

可以看到折線圖的 x 座標從 0 一直到了 40。

02 條形圖

上面的折線圖每次只有一個 y 值即可,而條形圖則需要所有的 y 值,如此所有的條形才能同時移動。

給 X 軸創建固定值,Y 軸創建列表,並使用 Matplotlib 的條形圖函數。

x = [1, 2, 3, 4, 5]
coordinates_lists = [[0, 0, 0, 0, 0],
                     [10, 30, 60, 30, 10],
                     [70, 40, 20, 40, 70],
                     [10, 20, 30, 40, 50],
                     [50, 40, 30, 20, 10],
                     [75, 0, 75, 0, 75],
                     [0, 0, 0, 0, 0]]
filenames = []
for index, y in enumerate(coordinates_lists):
    # 條形圖
    plt.bar(x, y)
    plt.ylim(0, 80)

    # 保存圖片文件
    filename = f'{index}.png'
    filenames.append(filename)

    # 重複最後一張圖形15幀(數值都爲0),15張圖片
    if (index == len(coordinates_lists) - 1):
        for i in range(15):
            filenames.append(filename)

    # 保存
    plt.savefig(filename)
    plt.close()

# 生成gif
with imageio.get_writer('mygif.gif'mode='I') as writer:
    for filename in filenames:
        image = imageio.imread(filename)
        writer.append_data(image)

# 刪除20張柱狀圖
for filename in set(filenames):
    os.remove(filename)

有數值的條形圖圖片是 5 張,沒數值的圖片是 2+15=17 張。

GIF 結束段,添加了 15 幀空白圖片。所以在結束的時候會顯示一段時間的空白。

可以設置一下條形圖當前位置到下個位置的速度,讓過渡變得平滑。

將當前位置和下一個位置之間的距離除以過渡幀數。

n_frames = 10
x = [1, 2, 3, 4, 5]
coordinates_lists = [[0, 0, 0, 0, 0],
                     [10, 30, 60, 30, 10],
                     [70, 40, 20, 40, 70],
                     [10, 20, 30, 40, 50],
                     [50, 40, 30, 20, 10],
                     [75, 0, 75, 0, 75],
                     [0, 0, 0, 0, 0]]
print('生成圖表\n')
filenames = []
for index in np.arange(0, len(coordinates_lists) - 1):
    # 獲取當前圖像及下一圖像的y軸座標值
    y = coordinates_lists[index]
    y1 = coordinates_lists[index + 1]

    # 計算當前圖像與下一圖像y軸座標差值
    y_path = np.array(y1) - np.array(y)
    for i in np.arange(0, n_frames + 1):
        # 分配每幀的y軸移動距離
        # 逐幀增加y軸的座標值
        y_temp = (y + (y_path / n_frames) * i)
        # 繪製條形圖
        plt.bar(x, y_temp)
        plt.ylim(0, 80)
        # 保存每一幀的圖像
        filename = f'images/frame_{index}_{i}.png'
        filenames.append(filename)
        # 最後一幀重複,畫面停留一會
        if (i == n_frames):
            for i in range(5):
                filenames.append(filename)
        # 保存圖片
        plt.savefig(filename)
        plt.close()
print('保存圖表\n')
# 生成GIF
print('生成GIF\n')
with imageio.get_writer('mybars.gif'mode='I') as writer:
    for filename in filenames:
        image = imageio.imread(filename)
        writer.append_data(image)
print('保存GIF\n')
print('刪除圖片\n')
# 刪除圖片
for filename in set(filenames):
    os.remove(filename)
print('完成')

看起來是平滑了許多。

好了,接下來我們更改一下圖表相關的配置參數,讓圖表變得好看。

n_frames = 10
bg_color = '#95A4AD'
bar_color = '#283F4E'
gif_name = 'bars'
x = [1, 2, 3, 4, 5]
coordinates_lists = [[0, 0, 0, 0, 0],
                     [10, 30, 60, 30, 10],
                     [70, 40, 20, 40, 70],
                     [10, 20, 30, 40, 50],
                     [50, 40, 30, 20, 10],
                     [75, 0, 75, 0, 75],
                     [0, 0, 0, 0, 0]]
print('生成圖表\n')
filenames = []
for index in np.arange(0, len(coordinates_lists) - 1):
    y = coordinates_lists[index]
    y1 = coordinates_lists[index + 1]
    y_path = np.array(y1) - np.array(y)
    for i in np.arange(0, n_frames + 1):
        y_temp = (y + (y_path / n_frames) * i)
        # 繪製條形圖
        fig, ax = plt.subplots(figsize=(8, 4))
        ax.set_facecolor(bg_color)
        plt.bar(x, y_temp, width=0.4, color=bar_color)
        plt.ylim(0, 80)
        # 移除圖表的上邊框和右邊框
        ax.spines['right'].set_visible(False)
        ax.spines['top'].set_visible(False)
        # 設置虛線網格線
        ax.set_axisbelow(True)
        ax.yaxis.grid(color='gray'linestyle='dashed'alpha=0.7)
        # 保存每一幀的圖像
        filename = f'images/frame_{index}_{i}.png'
        filenames.append(filename)

        # 最後一幀重複,畫面停留一會
        if (i == n_frames):
            for i in range(5):
                filenames.append(filename)
        # 保存圖片
        plt.savefig(filename, dpi=96, facecolor=bg_color)
        plt.close()
print('保存圖表\n')
# 生成GIF
print('生成GIF\n')
with imageio.get_writer(f'{gif_name}.gif'mode='I') as writer:
    for filename in filenames:
        image = imageio.imread(filename)
        writer.append_data(image)
print('保存GIF\n')
print('刪除圖片\n')
# 刪除圖片
for filename in set(filenames):
    os.remove(filename)
print('完成')

給圖表添加了背景色、條形圖上色、去除邊框、增加網格線等。

看起來,效果還不錯!

當然也有一些值得改進的地方,比如添加標題。通過插值的方式來使過渡變得更平滑,甚至可以讓條形圖在 x 軸上移動。

這裏大家就可以自行去研究啦。

03 散點圖

要繪製動態散點圖,則需要同時考慮 x 軸和 y 軸的值。

這裏不一定要在每幀上顯示相同數量的點,因此需要對其進行校正來進行過渡。

coordinates_lists = [[[0][0]],
                     [[100, 200, 300][100, 200, 300]],
                     [[400, 500, 600][400, 500, 600]],
                     [[400, 500, 600, 400, 500, 600][400, 500, 600, 600, 500, 400]],
                     [[500][500]],
                     [[0][0]]]
gif_name = 'movie'
n_frames = 10
bg_color = '#95A4AD'
marker_color = '#283F4E'
marker_size = 25
print('生成圖表\n')
filenames = []
for index in np.arange(0, len(coordinates_lists) - 1):
    # 獲取當前圖像及下一圖像的x與y軸座標值
    x = coordinates_lists[index][0]
    y = coordinates_lists[index][1]
    x1 = coordinates_lists[index + 1][0]
    y1 = coordinates_lists[index + 1][1]
    # 查看兩點差值
    while len(x) < len(x1):
        diff = len(x1) - len(x)
        x = x + x[:diff]
        y = y + y[:diff]
    while len(x1) < len(x):
        diff = len(x) - len(x1)
        x1 = x1 + x1[:diff]
        y1 = y1 + y1[:diff]
    # 計算路徑
    x_path = np.array(x1) - np.array(x)
    y_path = np.array(y1) - np.array(y)
    for i in np.arange(0, n_frames + 1):
        # 計算當前位置
        x_temp = (x + (x_path / n_frames) * i)
        y_temp = (y + (y_path / n_frames) * i)
        # 繪製圖表
        fig, ax = plt.subplots(figsize=(6, 6)subplot_kw=dict(aspect="equal"))
        ax.set_facecolor(bg_color)

        plt.scatter(x_temp, y_temp, c=marker_color, s=marker_size)
        plt.xlim(0, 1000)
        plt.ylim(0, 1000)
        # 移除邊框線
        ax.spines['right'].set_visible(False)
        ax.spines['top'].set_visible(False)
        # 網格線
        ax.set_axisbelow(True)
        ax.yaxis.grid(color='gray'linestyle='dashed'alpha=0.7)
        ax.xaxis.grid(color='gray'linestyle='dashed'alpha=0.7)
        # 保存圖片
        filename = f'images/frame_{index}_{i}.png'
        filenames.append(filename)
        if (i == n_frames):
            for i in range(5):
                filenames.append(filename)
        # 保存
        plt.savefig(filename, dpi=96, facecolor=bg_color)
        plt.close()
print('保存圖表\n')
# 生成GIF
print('生成GIF\n')
with imageio.get_writer(f'{gif_name}.gif'mode='I') as writer:
    for filename in filenames:
        image = imageio.imread(filename)
        writer.append_data(image)
print('保存GIF\n')
print('刪除圖片\n')
# 刪除圖片
for filename in set(filenames):
    os.remove(filename)
print('完成')

效果如下。

當然還有更有趣的散點圖變化,比如字母變化。

使用 OpenCV 從圖像創建 mask,繪製填充有隨機 x/y 座標的圖,並過濾 mask 內的點。 

使用 Matplotlib 繪製散點圖,使用 ImageIO 生成 gif。

import os
import numpy as np
import matplotlib.pyplot as plt
import imageio
import random
import cv2


# 根據字母的形狀, 將字母轉化爲多個隨機點
def get_masked_data(letter, intensity=2):
    # 多個隨機點填充字母
    random.seed(420)
    x = []
    y = []

    for i in range(intensity):
        x = x + random.sample(range(0, 1000), 500)
        y = y + random.sample(range(0, 1000), 500)

    if letter == ' ':
        return x, y

    # 獲取圖片的mask
    mask = cv2.imread(f'images/letters/{letter.upper()}.png', 0)
    mask = cv2.flip(mask, 0)

    # 檢測點是否在mask中
    result_x = []
    result_y = []
    for i in range(len(x)):
        if (mask[y[i]][x[i]]) == 0:
            result_x.append(x[i])
            result_y.append(y[i])

    # 返回x,y
    return result_x, result_y


# 將文字切割成一個個字母
def text_to_data(txt, repeat=True, intensity=2):
    print('將文本轉換爲數據\n')
    letters = []
    for i in txt.upper():
        letters.append(get_masked_data(i, intensity=intensity))
    # 如果repeat爲1時,重複第一個字母
    if repeat:
        letters.append(get_masked_data(txt[0]intensity=intensity))
    return letters


def build_gif(coordinates_lists, gif_name='movie'n_frames=10, bg_color='#95A4AD',
              marker_color='#283F4E'marker_size=25):
    print('生成圖表\n')
    filenames = []
    for index in np.arange(0, len(coordinates_lists) - 1):
        # 獲取當前圖像及下一圖像的x與y軸座標值
        x = coordinates_lists[index][0]
        y = coordinates_lists[index][1]

        x1 = coordinates_lists[index + 1][0]
        y1 = coordinates_lists[index + 1][1]

        # 查看兩點差值
        while len(x) < len(x1):
            diff = len(x1) - len(x)
            x = x + x[:diff]
            y = y + y[:diff]

        while len(x1) < len(x):
            diff = len(x) - len(x1)
            x1 = x1 + x1[:diff]
            y1 = y1 + y1[:diff]

        # 計算路徑
        x_path = np.array(x1) - np.array(x)
        y_path = np.array(y1) - np.array(y)

        for i in np.arange(0, n_frames + 1):
            # 計算當前位置
            x_temp = (x + (x_path / n_frames) * i)
            y_temp = (y + (y_path / n_frames) * i)

            # 繪製圖表
            fig, ax = plt.subplots(figsize=(6, 6)subplot_kw=dict(aspect="equal"))
            ax.set_facecolor(bg_color)
            plt.xticks([])  # 去掉x軸
            plt.yticks([])  # 去掉y軸
            plt.axis('off')  # 去掉座標軸

            plt.scatter(x_temp, y_temp, c=marker_color, s=marker_size)

            plt.xlim(0, 1000)
            plt.ylim(0, 1000)

            # 移除框線
            ax.spines['right'].set_visible(False)
            ax.spines['top'].set_visible(False)

            # 網格線
            ax.set_axisbelow(True)
            ax.yaxis.grid(color='gray'linestyle='dashed'alpha=0.7)
            ax.xaxis.grid(color='gray'linestyle='dashed'alpha=0.7)

            # 保存圖片
            filename = f'images/frame_{index}_{i}.png'

            if (i == n_frames):
                for i in range(5):
                    filenames.append(filename)

            filenames.append(filename)

            # 保存
            plt.savefig(filename, dpi=96, facecolor=bg_color)
            plt.close()
    print('保存圖表\n')
    # 生成GIF
    print('生成GIF\n')
    with imageio.get_writer(f'{gif_name}.gif'mode='I') as writer:
        for filename in filenames:
            image = imageio.imread(filename)
            writer.append_data(image)
    print('保存GIF\n')
    print('刪除圖片\n')
    # 刪除圖片
    for filename in set(filenames):
        os.remove(filename)

    print('完成')


coordinates_lists = text_to_data('Python'repeat=True, intensity=50)

build_gif(coordinates_lists,
          gif_name='Python',
          n_frames=7,
          bg_color='#52A9F0',
          marker_color='#000000',
          marker_size=0.2)

生成一個 Python 單詞字母的動態散點圖。

三個主要的函數。

# 創建一個隨機的x/y座標列表,並使用mask對其進行過濾。
get_masked_data()
# 將文本轉化爲數據
text_to_data()
# 使用座標點生成散點圖, 保存GIF
build_gif()

這裏小 F 給大家提供了 26 個字母,大夥可以自行組合。

當然其他圖形也是可以的,就是需要自己作圖。

圖片的大小應爲 1000x1000 像素,mask 着色爲黑色,背景爲白色。

然後將 png 文件保存在 images/letters 文件夾中,單獨一個字符命名。

coordinates_lists = text_to_data('mac_'repeat=True, intensity=50)

build_gif(coordinates_lists,
          gif_name='mac',
          n_frames=7,
          bg_color='#F5B63F',
          marker_color='#000000',
          marker_size=0.2)

結果如下,最後一張是個人物像。

好了,本期的分享就到此結束了。

使用 Matplotlib+Imageio 創建動態圖表,案例比較簡單,大家可以自行下載代碼進行學習。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/QUfh6oV6supZHW0dh5GqTg