matplotlib graphics window of scientific research drawing

matplotlib graphics window

Drawing objects (drawing window)

  1. Subgraph;
  2. Scale locator;
  3. Scale grid line;
  4. Semi logarithmic coordinates;

1. Drawing objects (drawing window)

matplotlib API for creating windows

# Manually create the matplotlib window
plt.figure(
    title='title',   # Window title bar text
    figsize=(4, 3),  # Window size (tuple)
    dpi=120,         # Pixel density
    facecolor=''     # Chart background color
)
plt.show()

The plt.figure method can build a new window. If the window with title='AAA 'has been built, PLT will not create a new window, but set the window with title='AAA' as the window of the current operation.

import matplotlib.pyplot as plt

plt.figure('A figure',facecolor='gray')  
# facecolor sets the window or palette to grayscale
plt.plot([0,1],[1,2])
plt.figure('B figure',facecolor='lightgray')
# facecolor sets the window or palette to light gray
plt.plot([1,2],[2,1])
# If the title in figure has been created, no new window will be created
# Instead, the old window (with the same window title) is set as the current window
plt.figure('A figure',facecolor='gray')
# Subsequent operations are also performed for 'A figure'
plt.plot([1,2],[2,1])
plt.show()

It can be seen from the displayed drawing results that a straight line with (1,2) and (2,1) as the endpoint is added in the A figure window.

2. Sets the parameters of the current window

From the image drawn above, we find that it lacks the title description, the scale value of the coordinate axis is too small and unclear, and there is no necessary text annotation of the coordinate axis. Therefore, the following methods are introduced:

  • Title of chart: plt.title()

  • Axis text: plt.xlabel() and plt.ylabel()

  • Tick mark parameter: plt.tick_params

  • Chart gridlines: plt.grid()

# Set the chart title, which is displayed above the chart
plt.title(title, fontsize=12)
# Sets the text for the horizontal axis
plt.xlabel(x_label_str, fontsize=12)
# Sets the text for the vertical axis
plt.ylabel(y_label_str, fontsize=12)
# Set the scale parameter and labelsize set the scale font size
plt.tick_params(labelsize=8)
# Set chart grid linestyle sets the style of the gridlines
"""
1. -  or solid     Thick line
2. -- or dashed    Dotted line
3. -. or dashdot   Dotted line
4. :  or dotted    Point line
"""
plt.grid(linestyle='')
# Set the compact layout and display the chart related parameters in the window
plt.tight_layout() 

Case: sinusoidal function y = s i n x y=sinx y=sinx as an example, test the relevant parameters of the window;

import matplotlib.pyplot as plt
import numpy as np

# Create a new window titled sinx figure
plt.figure('Sinx figure')
xdata = np.linspace(-2 * np.pi, 2 * np.pi, 100)
ydata = np.sin(xdata)
plt.plot(xdata, ydata, linewidth=2, alpha=0.9, color='dodgerblue')
plt.title(r'$y=sin(x)$', fontsize=18)
plt.xlabel('time', fontsize=16)
plt.ylabel('price', fontsize=16)
plt.grid(linestyle=':')
plt.tick_params(labelsize=14)
plt.tight_layout()
plt.savefig('sinx3.jpg')
plt.show()

What if you need to display Chinese fonts in the image drawn by matplotlib?

In the matplotlib drawing function, the display of Chinese Fonts is not supported by default, so you need to set it manually.

  • Global font settings
import matplotlib.pyplot as plt

# Global font settings
## Step 1: replace the default sans serif font
plt.rcParams['font.sans-serif'] = ['KaiTi']
## Step 2: solve the problem of displaying the negative sign of the negative number of the coordinate axis
plt.rcParams['axes.unicode_minus'] = False

xdata = np.linspace(0, 100, 1000)
ydata = -(xdata - 50) ** 2 + 5050
plt.plot(xdata, ydata, linewidth=2, alpha=0.9, color='dodgerblue')

plt.title("Relationship between speed and traffic flow",fontsize=16)
plt.xlabel("x axis",fontsize=16)
plt.ylabel("y axis",fontsize=16)
plt.savefig('fig2.png')
plt.show()

  • Local font settings
import matplotlib.pyplot as plt

# Local font setting. The font of title and coordinate axis can be set separately
plt.xlabel("x axis", fontproperties="SimSun")
plt.ylabel('y axis', fontproperties="SimSun")
plt.title("title", fontproperties="SimHei")
plt.show()

English names of some commonly used Chinese fonts (of course, the font style of the local system can also be used):

Chinese fontEnglish nameChinese fontEnglish name
Song typefaceSimSunChinese regular scriptSTKaiti
BlackbodySimHeiChinese Song typefaceSTSong
Microsoft YaHei Microsoft YaHeiChinese imitation Song DynastySTFangsong
Regular scriptKaiTiMicrosoft JhengHei Microsoft JhengHei
Imitation Song DynastyFangSongFine bright bodyMingLiU

3. Subgraph layout

API related to drawing matrix layout (common): plot.subplot (rows, cols, Num), where rows represents the number of rows, cols represents the number of columns, and num represents the number of subgraphs.

# The chart background color is set to bright gray
plt.figure('subplot Layout', facecolor='lightgray')
"""
plt.subplot(rows, cols, num)
rows: Number of rows
cols: Number of columns
num: number
"""
# Operate the subgraph numbered 5 in the matrix with 3 rows and 3 columns
plt.subplot(3, 3, 5)
# 1 2 3
# 4 5 6
# 7 8 9
plt.subplot(335)  # Abbreviation

Case: draw a nine palace lattice matrix subgraph, and write a number in each subgraph.

import numpy as np
import matplotlib.pyplot as plt

# Create a window
plt.figure('subplot', facecolor='lightgray')
for i in range(1, 10):
    plt.subplot(3, 3, i)  # Select subgraph
    plt.text(0.5, 0.5, str(i), ha='center', va='center',size=36,alpha=0.6)
    plt.xticks([])
    plt.yticks([])
    plt.tight_layout()
plt.show()

Through figure.add_aubplot() draws subgraphs

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Create a canvas or window
fig = plt.figure(figsize=(10, 8))

# Sub Figure 1
x = np.linspace(1, 10,100)
ax1 = fig.add_subplot(221)
ax1.plot(x, x ** 2)

# Subgraph 2
ax2 = fig.add_subplot(222)
ax2.scatter(x, np.random.rand(100), s=10)
ax2.set_xlim(0, 12)
ax2.set_ylim(0, 1.2)
ax2.spines['top'].set_color('none')  # Indicates that the top axis is not displayed
ax2.spines['right'].set_color('none')

# Sub Figure 3
ax3 = fig.add_subplot(223)
ax3.plot(x, np.log(x))
# How to add axis dimensions and titles to the subgraphs
# Operate the window parameters of the subgraph through ax3
ax3.set_title(r"$y=log(x)$")
ax3.set_xlabel("time")
ax3.set_ylabel("price")
ax3.legend()

# Sub Figure 4
ax4 = fig.add_subplot(224)
ax4.plot(x, np.sin(x))
plt.show()

The subgraph is drawn through plt.subplots(). The type of the value returned by subplots() is tuple, which contains two elements: the first is a canvas or window, and the second is the list of subgraphs;

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

fig, axes = plt.subplots(2, 2)

# Line chart
x1 = np.arange(1, 100)
y1 = x1 ** 2
axes[0][0].plot(x1, x1 ** 2)

# Scatter diagram
x2 = np.arange(0, 10)
y2 = np.random.rand(10)
axes[0][1].scatter(x2, y2)

# Pie chart
x3 = [15,30,45,10]  # The cumulative sum is 100
axes[1][0].pie(x3, labels=list('ABCD'), autopct='%.0f', explode=[0,0.05,0,0])

# Bar chart
x4 = ['A', 'B', 'C', 'D', 'E']
y4 = [25, 15, 35, 30, 20]
axes[1][1].bar(x4, y4, color='b')
plt.show()

4. Save the drawn image

Image storage formats supported by matplotlib: eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff.

The plt.savefig() function is used to save the drawn image. The parameters are as follows:

  1. filename: the name or path to save the picture file; required;
  2. Figsize: save the size of the output image, in inches, for example: figsize=[8, 8];
  3. dpi: the resolution of image saving (the higher the resolution, the clearer the image). The unit is pixel. Generally, it is set as dpi=600;
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-np.pi, np.pi, 1000)
sinx = np.sin(x)
cosx = 1/2 * np.cos(x)

plt.plot(x, sinx, linestyle='-.', linewidth=2, color='dodgerblue', label=r'$y=sin(x)$')
plt.plot(x, cosx, linestyle='--', linewidth=2, color='orangered', label=r'$y=\frac{1}{2}cos(x)$')
plt.legend(loc='upper left')
# Adjust the dpi resolution if the image is not clear enough
plt.savefig('figC.jpg', figsize=[8, 8], dpi=600)
plt.show()

5. Scale locator

API related to scale locator:

# Gets the current axis
ax = plt.gca()
# Sets the major scale locator for the horizontal axis
ax.xaxis.set_major_locator(plt.NullLocator(1))
# Set the sub scale locator of the horizontal coordinate axis as a multi-point locator with an interval of 0.1
ax.xaxis.set_minor_locator(plt.MultipleLocator(0,1))

Case: draw a number axis;

import matplotlib.pyplot as plt

plt.figure(figsize=(8, 6), dpi=100)
# Gets the current axis
plt.xlim(0, 10)
ax = plt.gca()
# Hide all axes except the bottom axis
ax.spines['left'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
# Adjust the bottom coordinate axis to the center of the sub drawing
ax.spines['bottom'].set_position(('data',0))
plt.yticks([])
# Sets the locator for the major scale of the horizontal axis
ax.xaxis.set_major_locator(plt.MultipleLocator(1))
# Set the sub scaler of the horizontal coordinate axis as a multipoint locator with an interval of 0.1
ax.xaxis.set_minor_locator(plt.MultipleLocator(0.2))
# Mark the scale locator class name used 
plt.text(5, 0.3,s='MultipleLocator', ha='center', size=14)
plt.show()

6. Scale grid line

API for drawing scale gridlines

ax = plt.gca()
# Draw scale gridlines
ax.grid(
    which='',      # Set major / minor. The default is major
    axis='',       # x / y / both, the default is both
    linewidth=1,   # line width
    linestyle=''   # Line type
    color='',      # Color, gray by default
    alpha=0.5      # transparency
)
import matplotlib.pyplot as plt
import numpy as np

plt.figure('Grid Line',figsize=(8, 6))
x = np.linspace(-2 * np.pi, 2 * np.pi, 100)
y = np.cos(x)
plt.plot(x, y, linestyle='--', color='dodgerblue',linewidth=1.5)
plt.title(r"$y=cos(x)$",fontsize=16)
plt.xlabel("x", fontsize=16)
plt.ylabel("y", fontsize=16)
plt.grid(linestyle=":")  # Use the default parameter major/both
plt.show()

Comprehensive case: draw the curve [1, 10, 100, 1000, 100, 10, 1], then set the scale grid line and test the parameters of the scale grid line.

import matplotlib.pyplot as plt

plt.figure('Grid Line',figsize=(8, 6))
ax = plt.gca()
# Modify the scale locator for x and y
ax.xaxis.set_major_locator(plt.MultipleLocator(1))
ax.xaxis.set_minor_locator(plt.MultipleLocator(0.2))

ax.yaxis.set_major_locator(plt.MultipleLocator(250))
ax.yaxis.set_minor_locator(plt.MultipleLocator(50))
# Draw gridlines
ax.grid(which='major', axis='both',
       color='orangered',linewidth=0.5)
ax.grid(which='minor', axis='both',
       color='orangered',linewidth=0.1)
# draw a curve
y = [1, 10, 100, 1000, 100, 10, 1]
plt.plot(y, 'o-', color='dodgerblue',linewidth=0.75)
plt.savefig("fig1.png")
plt.show()

**Semilogarithmic coordinates: * * y axis will increase exponentially, i.e.: plt.semilogy().

Draw the second subgraph based on semi logarithmic coordinates to represent the curve: [1, 10, 100, 1000, 100, 10, 1].

import matplotlib.pyplot as plt

plt.figure('Grid Line',figsize=(8, 6))
ax = plt.gca()
# Modify the scale locator for x and y
ax.xaxis.set_major_locator(plt.MultipleLocator(1))
ax.xaxis.set_minor_locator(plt.MultipleLocator(0.2))

ax.yaxis.set_major_locator(plt.MultipleLocator(250))
ax.yaxis.set_minor_locator(plt.MultipleLocator(50))
ax.grid(which='major', axis='both',
       color='orangered',linewidth=0.5)
ax.grid(which='minor', axis='both',
       color='orangered',linewidth=0.1)
# draw a curve
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 10, 100, 1000, 100, 10, 1]
plt.semilogy(x, y, 'o-', color='dodgerblue',linewidth=0.75)
plt.savefig("fig3.png")
plt.show()

Tags: Python matplotlib

Posted on Tue, 23 Nov 2021 10:09:34 -0500 by everydayrun