< Back

Env

import numpy as np
from matplotlib_inline import backend_inline
from d2l import torch as d2l
// 'from matplotlib import pyplot as plt' Saved to d2l


Set display format

def use_svg_display():  #@save
    """Use the svg format to display a plot in Jupyter."""
    backend_inline.set_matplotlib_formats('svg')


Set figure size

def set_figsize(figsize=(3.5, 2.5)): #@save
    """Set the figure size for matplotlib."""
    use_svg_display()
    d2l.plt.rcParams['figure.figsize'] = figsize
    d2l.plt.rcParams['text.antialiased'] = True
    d2l.plt.rcParams['font.sans-serif'] = ['Inter', 'DejaVu Sans', 'SimHei']


Set axes

def set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend): #@save
    """Set the axes for matplotlib."""
    axes.set_xlabel(xlabel)
    axes.set_ylabel(ylabel)
    axes.set_xscale(xscale)
    axes.set_yscale(yscale)
    axes.set_xlim(xlim)
    axes.set_ylim(ylim)
    
    # hide
    axes.spines['top'].set_visible(False)
    axes.spines['right'].set_visible(False)
    axes.spines['left'].set_color('#cccccc')
    axes.spines['bottom'].set_color('#cccccc')
    
    # grid
    axes.grid(True, linestyle='--', alpha=0.5, color='#e0e0e0', linewidth=0.6)
    
    if legend:
        leg = axes.legend(legend, frameon=True, facecolor=(1, 1, 1, 0.8), edgecolor='none')
        leg.get_frame().set_boxstyle("round,pad=0.3")
        for text in leg.get_texts():
            text.set_color('#444444')
            text.set_fontsize(9)


Draw

def plot(X, Y=None, xlabel=None, ylabel=None, legend=None, xlim=None,
         ylim=None, xscale='linear', yscale='linear',
         # Deep sea blue, soft purple, sage green, coral brick red
         fmts=('#2A4B7C', '#8E7AA3', '#728F70', '#C27D78'), 
         linewidth=1.8, figsize=(4.5, 3.2), axes=None): #@save
    """Plot data points."""
    if legend is None:
        legend = []
    set_figsize(figsize)
    axes = axes if axes else d2l.plt.gca()

    # if X has one axis, output ture
    def has_one_axis(X):
        return (hasattr(X, "ndim") and X.ndim == 1) or isinstance(X, list) and not hasattr(X[0], "__len__")
    
    if has_one_axis(X):
        X = [X]
    if Y is None:
        X, Y = [[]] * len(X), X
    elif has_one_axis(Y):
        Y = [Y]
    if len(X) != len(Y):
        X = X * len(Y)
        
    axes.cla()
    
    for i, (x, y, color) in enumerate(zip(X, Y, fmts)):
        # line2
        linestyle = '--' if i == 1 else '-'
        lw = linewidth * 0.8 if i == 1 else linewidth
        
        if len(x):
            axes.plot(x, y, color=color, linestyle=linestyle, linewidth=lw, antialiased=True)
        else:
            axes.plot(y, color=color, linestyle=linestyle, linewidth=lw, antialiased=True)
            
    set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend)


e.g.

x = np.arange(0, 3, 0.1)
plot(x, [f(x), 2*x-3], 'x', 'f(x)', legend=['f(x)', 'Tangent line (x=1)'])
def f(x)
def f(x):
    return 3 * x ** 2 - 4 * x