美文网首页
Subplots, axes and figures

Subplots, axes and figures

作者: itroger | 来源:发表于2018-05-27 19:43 被阅读0次

    1. Axes Props

    你可以控制坐标轴刻度和网格属性


    import matplotlib.pyplot as plt
    import numpy as np
    
    t = np.arange(0.0, 2.0, 0.01)
    s = np.sin(2 * np.pi * t)
    
    fig, ax = plt.subplots()
    ax.plot(t, s)
    
    ax.grid(True, linestyle='-.')
    ax.tick_params(labelcolor='r', labelsize='medium', width=3)
    
    plt.show()
    

    2. Invert Axes

    通过翻转坐标轴限制的正常顺序,可以使用递减轴


    import matplotlib.pyplot as plt
    import numpy as np
    
    t = np.arange(0.01, 5.0, 0.01)
    s = np.exp(-t)
    plt.plot(t, s)
    
    plt.xlim(5, 0)  # decreasing time
    
    plt.xlabel('decreasing time (s)')
    plt.ylabel('voltage (mV)')
    plt.title('Should be growing...')
    plt.grid(True)
    
    plt.show()
    

    3. Subplot Toolbar

    Matplotlib 有一个工具栏可用于调整 suplot 间距。



    import matplotlib.pyplot as plt
    import numpy as np
    
    fig, axs = plt.subplots(2, 2)
    
    axs[0, 0].imshow(np.random.random((100, 100)))
    
    axs[0, 1].imshow(np.random.random((100, 100)))
    
    axs[1, 0].imshow(np.random.random((100, 100)))
    
    axs[1, 1].imshow(np.random.random((100, 100)))
    
    plt.subplot_tool()
    plt.show()
    

    4. Multiple Figs Demo

    使用多个图形窗口和 subplots

    import matplotlib.pyplot as plt
    import numpy as np
    
    t = np.arange(0.0, 2.0, 0.01)
    s1 = np.sin(2*np.pi*t)
    s2 = np.sin(4*np.pi*t)
    

    创建图1

    plt.figure(1)
    plt.subplot(211)
    plt.plot(t, s1)
    plt.subplot(212)
    plt.plot(t, 2*s1)
    

    创建图2

    plt.figure(2)
    plt.plot(t, s2)
    

    现在切换回图1并进行一些更改

    plt.figure(1)
    plt.subplot(211)
    plt.plot(t, s2, 's')
    ax = plt.gca()
    ax.set_xticklabels([])
    
    plt.show()
    

    5. Multiple subplots

    具有多个 subplots 的简单演示


    import numpy as np
    import matplotlib.pyplot as plt
    
    
    x1 = np.linspace(0.0, 5.0)
    x2 = np.linspace(0.0, 2.0)
    
    y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
    y2 = np.cos(2 * np.pi * x2)
    
    plt.subplot(2, 1, 1)
    plt.plot(x1, y1, 'o-')
    plt.title('A tale of 2 subplots')
    plt.ylabel('Damped oscillation')
    
    plt.subplot(2, 1, 2)
    plt.plot(x2, y2, '.-')
    plt.xlabel('time (s)')
    plt.ylabel('Undamped')
    
    plt.show()
    

    6. Subplots Adjust

    使用 subplots_adjust() 调整边距和 subplots 的间距。

    import matplotlib.pyplot as plt
    import numpy as np
    
    # Fixing random state for reproducibility
    np.random.seed(19680801)
    
    
    plt.subplot(211)
    plt.imshow(np.random.random((100, 100)), cmap=plt.cm.BuPu_r)
    plt.subplot(212)
    plt.imshow(np.random.random((100, 100)), cmap=plt.cm.BuPu_r)
    
    plt.subplots_adjust(bottom=0.1, right=0.8, top=0.9)
    cax = plt.axes([0.85, 0.1, 0.075, 0.8])
    plt.colorbar(cax=cax)
    plt.show()
    

    7. Geographic Projections

    这显示了使用了 subplot 的4种可能的预测。Matplotlib 还支持Basemaps ToolkitCartopy 地理预测。

    import matplotlib.pyplot as plt
    
    plt.figure()
    plt.subplot(111, projection="aitoff")
    plt.title("Aitoff")
    plt.grid(True)
    
    plt.figure()
    plt.subplot(111, projection="hammer")
    plt.title("Hammer")
    plt.grid(True)
    
    plt.figure()
    plt.subplot(111, projection="lambert")
    plt.title("Lambert")
    plt.grid(True)
    
    plt.figure()
    plt.subplot(111, projection="mollweide")
    plt.title("Mollweide")
    plt.grid(True)
    
    plt.show()
    

    8. Basic Subplot Demo

    两个 subplots 演示。有关更多选项,请参阅 Subplots Demo

    import numpy as np
    import matplotlib.pyplot as plt
    
    # Data for plotting
    x1 = np.linspace(0.0, 5.0)
    x2 = np.linspace(0.0, 2.0)
    y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
    y2 = np.cos(2 * np.pi * x2)
    
    # Create two subplots sharing y axis
    fig, (ax1, ax2) = plt.subplots(2, sharey=True)
    
    ax1.plot(x1, y1, 'ko-')
    ax1.set(title='A tale of 2 subplots', ylabel='Damped oscillation')
    
    ax2.plot(x2, y2, 'r.-')
    ax2.set(xlabel='time (s)', ylabel='Undamped')
    
    plt.show()
    

    9. Custom Figure Class

    如果要从默认图形派生,可以将自定义图形构造函数传递给图。这个简单的示例创建一个具有图形标题的图形。


    import matplotlib.pyplot as plt
    from matplotlib.figure import Figure
    
    
    class MyFigure(Figure):
        def __init__(self, *args, **kwargs):
            """
            custom kwarg figtitle is a figure title
            """
            figtitle = kwargs.pop('figtitle', 'hi mom')
            Figure.__init__(self, *args, **kwargs)
            self.text(0.5, 0.95, figtitle, ha='center')
    
    
    fig = plt.figure(FigureClass=MyFigure, figtitle='my title')
    ax = fig.subplots()
    ax.plot([1, 2, 3])
    
    plt.show()
    

    10. Shared Axis Demo

    import matplotlib.pyplot as plt
    import numpy as np
    
    t = np.arange(0.01, 5.0, 0.01)
    s1 = np.sin(2 * np.pi * t)
    s2 = np.exp(-t)
    s3 = np.sin(4 * np.pi * t)
    
    ax1 = plt.subplot(311)
    plt.plot(t, s1)
    plt.setp(ax1.get_xticklabels(), fontsize=6)
    
    # share x only
    ax2 = plt.subplot(312, sharex=ax1)
    plt.plot(t, s2)
    # make these tick labels invisible
    plt.setp(ax2.get_xticklabels(), visible=False)
    
    # share x and y
    ax3 = plt.subplot(313, sharex=ax1, sharey=ax1)
    plt.plot(t, s3)
    plt.xlim(0.01, 5.0)
    plt.show()
    

    11. Zooming in and out using Axes.margins

    此示例演示如何使用 margins 而不是 set_xlimset_ylim

    import numpy as np
    import matplotlib.pyplot as plt
    
    
    def f(t):
        return np.exp(-t) * np.cos(2*np.pi*t)
    
    
    t1 = np.arange(0.0, 3.0, 0.01)
    
    ax1 = plt.subplot(212)
    ax1.margins(0.05)           # Default margin is 0.05, value 0 means fit
    ax1.plot(t1, f(t1), 'k')
    
    ax2 = plt.subplot(221)
    ax2.margins(2, 2)           # Values >0.0 zoom out
    ax2.plot(t1, f(t1), 'r')
    ax2.set_title('Zoomed out')
    
    ax3 = plt.subplot(222)
    ax3.margins(x=0, y=-0.25)   # Values in (-0.5, 0.0) zooms in to center
    ax3.plot(t1, f(t1), 'g')
    ax3.set_title('Zoomed in')
    
    plt.show()
    

    12. Creating adjacent subplots

    import matplotlib.pyplot as plt
    import numpy as np
    
    t = np.arange(0.0, 2.0, 0.01)
    
    s1 = np.sin(2 * np.pi * t)
    s2 = np.exp(-t)
    s3 = s1 * s2
    
    fig, axs = plt.subplots(3, 1, sharex=True)
    # Remove horizontal space between axes
    fig.subplots_adjust(hspace=0)
    
    # Plot each graph, and manually set the y tick values
    axs[0].plot(t, s1)
    axs[0].set_yticks(np.arange(-0.9, 1.0, 0.4))
    axs[0].set_ylim(-1, 1)
    
    axs[1].plot(t, s2)
    axs[1].set_yticks(np.arange(0.1, 1.0, 0.2))
    axs[1].set_ylim(0, 1)
    
    axs[2].plot(t, s3)
    axs[2].set_yticks(np.arange(-0.9, 1.0, 0.4))
    axs[2].set_ylim(-1, 1)
    
    plt.show()
    

    13. Aligning Labels

    import matplotlib.pyplot as plt
    import numpy as np
    import matplotlib.gridspec as gridspec
    
    fig = plt.figure(tight_layout=True)
    gs = gridspec.GridSpec(2, 2)
    
    ax = fig.add_subplot(gs[0, :])
    ax.plot(np.arange(0, 1e6, 1000))
    ax.set_ylabel('YLabel0')
    ax.set_xlabel('XLabel0')
    
    for i in range(2):
        ax = fig.add_subplot(gs[1, i])
        ax.plot(np.arange(1., 0., -0.1) * 2000., np.arange(1., 0., -0.1))
        ax.set_ylabel('YLabel1 %d' % i)
        ax.set_xlabel('XLabel1 %d' % i)
        if i == 0:
            for tick in ax.get_xticklabels():
                tick.set_rotation(55)
    fig.align_labels()  # same as fig.align_xlabels(); fig.align_ylabels()
    
    plt.show()
    

    相关文章

      网友评论

          本文标题:Subplots, axes and figures

          本文链接:https://www.haomeiwen.com/subject/guhijftx.html