python繪圖 ——繪製常用圖形(matplotlib、pyecharts、plotly)

1 plotly畫柱狀圖和折線圖

#柱狀圖+折線圖
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(
    go.Scatter(
        x=[0, 1, 2, 3, 4, 5],
        y=[1.5, 1, 1.3, 0.7, 0.8, 0.9]
    ))
fig.add_trace(
    go.Bar(
        x=[0, 1, 2, 3, 4, 5],
        y=[2, 0.5, 0.7, -1.2, 0.3, 0.4]
    ))
fig.show()

測試結果:
在這裏插入圖片描述

2 seaborn繪製熱力圖

# 導入庫
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# 生成數據集
data = np.random.random((6,6))
np.fill_diagonal(data,np.ones(6))
features = ["prop1","prop2","prop3","prop4","prop5", "prop6"]
data = pd.DataFrame(data, index = features, columns=features)
print(data)
# 繪製熱力圖
heatmap_plot = sns.heatmap(data, center=0, cmap='gist_rainbow')
plt.show()

測試結果:
在這裏插入圖片描述

3 matplotlib繪製折線圖

先定義一個函數模塊,名稱爲:example_utils.py,裏面包括三個函數,各自功能如下:

import matplotlib.pyplot as plt

# 創建畫圖fig和axes
def setup_axes():
    fig, axes = plt.subplots(ncols=3, figsize=(6.5,3))
    for ax in fig.axes:
        ax.set(xticks=[], yticks=[])
    fig.subplots_adjust(wspace=0, left=0, right=0.93)
    return fig, axes
# 圖片標題
def title(fig, text, y=0.9):
    fig.suptitle(text, size=14, y=y, weight='semibold', x=0.98, ha='right',
                 bbox=dict(boxstyle='round', fc='floralwhite', ec='#8B7E66',
                           lw=2))
# 爲數據添加文本註釋
def label(ax, text, y=0):
    ax.annotate(text, xy=(0.5, 0.00), xycoords='axes fraction', ha='center',
                style='italic',
                bbox=dict(boxstyle='round', facecolor='floralwhite',
                          ec='#8B7E66'))

繪製折線圖代碼:

import numpy as np
import matplotlib.pyplot as plt
import example_utils

x = np.linspace(0, 10, 100)
fig, axes = example_utils.setup_axes()
for ax in axes:
    ax.margins(y=0.10)
# 子圖1 默認plot多條線,顏色系統分配
for i in range(1, 6):
    axes[0].plot(x, i * x)

# 子圖2 展示線的不同linestyle
for i, ls in enumerate(['-', '--', ':', '-.']):
    axes[1].plot(x, np.cos(x) + i, linestyle=ls)

# 子圖3 展示線的不同linestyle和marker
for i, (ls, mk) in enumerate(zip(['', '-', ':'], ['o', '^', 's'])):
    axes[2].plot(x, np.cos(x) + i * x, linestyle=ls, marker=mk, markevery=10)

# 設置標題
# example_utils.title(fig, '"ax.plot(x, y, ...)": Lines and/or markers', y=0.95)
# 保存圖片
fig.savefig('plot_example.png', facecolor='none')
# 展示圖片
plt.show()

在這裏插入圖片描述

4 matplotlib散點圖

先定義一個函數模塊名稱爲:example_utils.py,裏面包括三個函數,源代碼同上折線圖
散點圖代碼:

"""
散點圖的基本用法
"""
import numpy as np
import matplotlib.pyplot as plt
import example_utils

# 隨機生成數據
np.random.seed(1874)
x, y, z = np.random.normal(0, 1, (3, 100))
t = np.arctan2(y, x)
size = 50 * np.cos(2 * t)**2 + 10
fig, axes = example_utils.setup_axes()
# 子圖1
axes[0].scatter(x, y, marker='o',  color='darkblue', facecolor='white', s=80)
example_utils.label(axes[0], 'scatter(x, y)')
# 子圖2
axes[1].scatter(x, y, marker='s', color='darkblue', s=size)
example_utils.label(axes[1], 'scatter(x, y, s)')
# 子圖3
axes[2].scatter(x, y, s=size, c=z,  cmap='gist_ncar')
example_utils.label(axes[2], 'scatter(x, y, s, c)')
# example_utils.title(fig, '"ax.scatter(...)": Colored/scaled markers',#                     y=0.95)
fig.savefig('scatter_example.png', facecolor='none')
plt.show()

在這裏插入圖片描述

5 matplotlib柱狀圖

import numpy as np
import matplotlib.pyplot as plt

import example_utils


def main():
    fig, axes = example_utils.setup_axes()

    basic_bar(axes[0])
    tornado(axes[1])
    general(axes[2])

    # example_utils.title(fig, '"ax.bar(...)": Plot rectangles')
    fig.savefig('bar_example.png', facecolor='none')
    plt.show()

# 子圖1
def basic_bar(ax):
    y = [1, 3, 4, 5.5, 3, 2]
    err = [0.2, 1, 2.5, 1, 1, 0.5]
    x = np.arange(len(y))
    ax.bar(x, y, yerr=err, color='lightblue', ecolor='black')
    ax.margins(0.05)
    ax.set_ylim(bottom=0)
    example_utils.label(ax, 'bar(x, y, yerr=e)')

# 子圖2
def tornado(ax):
    y = np.arange(8)
    x1 = y + np.random.random(8) + 1
    x2 = y + 3 * np.random.random(8) + 1
    ax.barh(y, x1, color='lightblue')
    ax.barh(y, -x2, color='salmon')
    ax.margins(0.15)
    example_utils.label(ax, 'barh(x, y)')

# 子圖3
def general(ax):
    num = 10
    left = np.random.randint(0, 10, num)
    bottom = np.random.randint(0, 10, num)
    width = np.random.random(num) + 0.5
    height = np.random.random(num) + 0.5
    ax.bar(left, height, width, bottom, color='salmon')
    ax.margins(0.15)
    example_utils.label(ax, 'bar(l, h, w, b)')
##運行
if __name__=="__main__":
    main()

在這裏插入圖片描述

6 matplotlib等高線圖

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.cbook import get_sample_data

import example_utils

z = np.load(get_sample_data('bivariate_normal.npy'))

fig, axes = example_utils.setup_axes()

axes[0].contour(z, cmap='gist_earth')
example_utils.label(axes[0], 'contour')

axes[1].contourf(z, cmap='gist_earth')
example_utils.label(axes[1], 'contourf')

axes[2].contourf(z, cmap='gist_earth')
cont = axes[2].contour(z, colors='black')
axes[2].clabel(cont, fontsize=6)
example_utils.label(axes[2], 'contourf + contour\n + clabel')

# example_utils.title(fig, '"contour, contourf, clabel": Contour/label 2D data',
#                     y=0.96)
fig.savefig('contour_example.png', facecolor='none')

plt.show()

在這裏插入圖片描述

7 matplotlib繪製動畫

matplotlib是python中最經典的繪圖包,裏面animation模塊能繪製動畫。

首先導入小例子使用的模塊:

from matplotlib import pyplot as plt
from matplotlib import animation
from random import randint, random

生成數據,frames_count是幀的個數,data_count每個幀的柱子個數

class Data:
    data_count = 32
    frames_count = 2

    def __init__(self, value):
        self.value = value
        self.color = (0.5, random(), random()) #rgb

    # 造數據
    @classmethod
    def create(cls):
        return [[Data(randint(1, cls.data_count)) for _ in range(cls.data_count)]
                for frame_i in range(cls.frames_count)]

繪製動畫:animation.FuncAnimation函數的回調函數的參數fi表示第幾幀,注意要調用axs.cla()清除上一幀。

def draw_chart():
    fig = plt.figure(1, figsize=(16, 9))
    axs = fig.add_subplot(111)
    axs.set_xticks([])
    axs.set_yticks([])
    # 生成數據
    frames = Data.create()
    def animate(fi):
        axs.cla()  # clear last frame
        axs.set_xticks([])
        axs.set_yticks([])
        return axs.bar(list(range(Data.data_count)),        # X
                       [d.value for d in frames[fi]],       # Y
                       1,                                   # width
                       color=[d.color for d in frames[fi]]  # color
                       )
    # 動畫展示
    anim = animation.FuncAnimation(fig, animate, frames=len(frames))
    plt.show()
draw_chart()

測試結果:
在這裏插入圖片描述
繪圖素材和參考來源:https://github.com/jackzhenguo/python-small-examples

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章