“This is the 19th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”

Ebook address: github.com/rougier/sci…

Recommended open source technical details matplotlib’s book: Scientific-Visualization Book. It mainly introduces the introduction and basic principles of Matplotlib library, graphic design, graphic layout and organization, 3D graphics and animation, etc.

directory

anatomy of figure

As shown above, the Matplotlib graph consists of a hierarchy of elements that are combined to form the actual graph, and it is important to understand the different elements of the graph.

The element

Figure

The most important element of figure is figure itself. It is created when the figure method is called, and we have seen that you can specify its size as well as the background color (facecolor) and title (Suptitle). It is important to know that the background color is not used when saving the figure, because the SaveFig function also has a Facecolor parameter (white by default) that overrides the figure’s background color. If you don’t need any background, you can specify transparent=True when saving the figure.

Axes

Axes is the second most important element, which corresponds to the actual presentation area of the data. It is also called a subplot. Each figure can have one to more axes, and each axis is usually surrounded by four edges (left, up, right, and down) called spines. Each of these spines can be decorated with major ticks and minor ticks (pointing inward or outward, respectively), tick labels and labels.

Axis

These decorated spines are called axes. The horizontal direction is the X axis, and the vertical direction is the Y axis. Each consists of spine, major ticks and minor Ticks, primary and secondary ticks labels, and axis labels.

Spines

Spines are lines that connect the axis scale lines and mark the boundaries of the data area. They can be placed anywhere and can be visible or invisible.

Artist

Everything on a graph, including graphs, axes, and axis objects, is artist. This includes text objects, Line2D objects, collection objects, and facets objects. When rendering a character, all artists are drawn onto the canvas. A given artist can only be on one axis.

Apply colours to a drawing

The author also gives detailed Settings for matplotlib rendering

import matplotlib
matplotlib.use("xxx")
Copy the code

Dimensions and resolution

fig = plt.figure(figsize=(6.6))
plt.savefig("output.png")
Copy the code

Matplotlib’s default DPI is 100, which corresponds to a resolution of 6 inches by 6 inches. For a Scientific article, publishers will usually require figures DPI between 300 and 600. To get the DPI setup right, we need to know the physical size of the graphic to insert into the document.

The author provides a more concrete example, let’s consider the format of this book is A5 (148 x 210 mm). Margins are 20 mm on the left and 20 mm on the right, and images are typically displayed in full-text width. This means that the physical width of the image is exactly 108 millimeters, or about 4.25 inches. If we use the recommended 600 Dpi, we end up with 2550 pixels in width, which is probably beyond the screen resolution and therefore inconvenient. Instead, we can use the default matplotlib DPI (100) when we display graphics on the screen, and only use a different and higher DPI when we save graphics:

def figure(dpi) :
    fig = plt.figure(figsize=(4.25.2.))
    ax = plt.subplot(1.1.1)
    text = "Text rendered at 10pt using %d dpi" % dpi
    ax.text(0.5.0.5, text, ha="center", va="center",
            fontname="Source Serif Pro",
            fontsize=10, fontweight="light")
    plt.savefig("figure-dpi-%03d.png" % dpi, dpi=dpi)
    
figure(50), figure(100), figure(300), figure(600)
Copy the code

The author provides many useful research mapping exercises

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

def curve() :
    n = np.random.randint(1.5)
    centers = np.random.normal(0.0.1.0,n)
    widths = np.random.uniform(5.0.50.0,n)
    widths = 10*widths/widths.sum()
    scales = np.random.uniform(0.1.1.0,n)
    scales /= scales.sum()
    X = np.zeros(500)
    x = np.linspace(-3.3.len(X))
    for center, width, scale in zip(centers, widths, scales):
        X = X + scale*np.exp(- (x-center)*(x-center)*width)
    return X

np.random.seed(123)
cmap = mpl.cm.get_cmap("Spectral")
fig = plt.figure(figsize=(8.8))

ax = None
for n in range(3):
    ax = plt.subplot(1.3, n + 1, frameon=False, sharex=ax)
    for i in range(50):
        Y = curve()
        X = np.linspace(-3.3.len(Y))
        ax.plot(X, 3 * Y + i, color="k", linewidth=0.75, zorder=100 - i)
        color = cmap(i / 50)
        ax.fill_between(X, 3 * Y + i, i, color=color, zorder=100 - i)

        # Some random text on the right of the curve
        v = np.random.uniform(0.1)
        if v < 0.4:
            text = "*"
            if v < 0.05:
                text = "* * *"
            elif v < 0.2:
                text = "* *"
            ax.text(
                3.0,
                i,
                text,
                ha="right",
                va="baseline",
                size=8,
                transform=ax.transData,
                zorder=300,
            )

    ax.yaxis.set_tick_params(tick1On=False)
    ax.set_xlim(-3.3)
    ax.set_ylim(-1.53)
    ax.axvline(0.0, ls="--", lw=0.75, color="black", zorder=250)
    ax.text(
        0.0.1.0."Value %d" % (n + 1),
        ha="left",
        va="top",
        weight="bold",
        transform=ax.transAxes,
    )

    if n == 0:
        ax.yaxis.set_tick_params(labelleft=True)
        ax.set_yticks(np.arange(50))
        ax.set_yticklabels(["Serie %d" % i for i in range(1.51)])
        for tick in ax.yaxis.get_major_ticks():
            tick.label.set_fontsize(6)
            tick.label.set_verticalalignment("bottom")
    else:
        ax.yaxis.set_tick_params(labelleft=False)


plt.tight_layout()
plt.savefig("./zorder-plots.png", dpi=600)
plt.savefig("./zorder-plots.pdf")
plt.show()
Copy the code

References:

[1] Nicolas Rougier. Scientific Visualization: Python + Matplotlib. Nicolas P. Rougier. 2021, 978-2- 9579901-0-8. hal-03427242