Advanced usage of Python using the plot() function to draw pictures

Table of contents

Introduction

Advanced use of plot() function

(1) Global information code

(2) Drawing code

(1) Canvas Settings

(2) Function incoming parameter setting

(3) Interpretation of the internal code of the function

(4) Function call

(5) Use of the plt.tight_layout() function

(6) Finally, the graphics are made as follows


Introduction

In the previous article "Python directly uses the plot() function to draw pictures" mentioned the plot() function, the simplest function in the matplotlib library, and introduced the simplest method of using plot(), including the parameters in the plot() function and the basic settings of the canvas , simple data into the drawing, this advanced use, we will set the parameters in the drawing through the function method, and also explain the drawing of multiple line charts and the selection of data.

Using function drawing has the advantages of convenient calling of graphics, simple parameter setting, and high code reusability.

The data used in this drawing is the crop yield change data from 2001 to 2021. The data includes statistical time, grain production (10,000 tons), grain production growth (%), cotton (10,000 tons), cotton growth (%), oilseeds (10,000 tons), and oilseeds growth (%).

Advanced use of plot() function

Requirements for the experiment: Draw the trend charts of grain and oil crops and the growth rate charts of grain and oil crops

Drawing requirements: labels are clear, two are presented in one canvas, legends are set, private labels are added

(1) Global information code

# 导入所需模块
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import warnings

# 设置全局变量
warnings.filterwarnings("ignore")
plt.rcParams['font.sans-serif'] = ['Microsoft Yahei']
plt.rcParams['axes.unicode_minus'] = False

#数据读入
df = pd.read_excel(r'作物产量.xls')

① Import data processing related libraries (pandas, numpy) and import drawing library (matplotlib)

②Set warning filter: warning filter [warnings.filterwarnings("ignore")]

Used to control the behavior of warning messages, such as ignoring, displaying or converting to errors (throwing exceptions)

Where the parameter ignore is to ignore matching warnings

③plt.rcParams setting parameters

plt.rcParams['font.sans-serif'] The font (font) in the running configuration parameters is Microsoft Yahei

plt.rcParams['axes.unicode_minus'] = False #The total axes (axes) of the running configuration parameters normally display the sign (minus)

(2) Drawing code

# 将每一组数据画到同一个坐标子图中

f,(ax1,ax2) = plt.subplots(2,1,figsize=(6,6),dpi=100)
def draw_a(ax,df,x_col=0,y_cols=[1],colors=None,makers=None,title='',myname='',ylabel=''):
    X = df.iloc[:,x_col]  # Series
    Y = df.iloc[:,y_cols]
    title = "【"+myname+"】" + title
    xlabel = "【"+myname+"】" + df.columns[x_col]
    ylabel = "【"+myname+"】" + ylabel

    for i in Y.columns:
        ax.plot(X,Y[i],label=i)
        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)
        ax.set_xticklabels(X,rotation=90,fontsize=8)
        ax.set_yticklabels(ax.get_yticks(),fontsize=8)
        ax.set_title(title)
        ax.legend()

draw_a(ax1,df,x_col=0,y_cols=[1,5],title="2001-2021年粮食、油料产量走势折线图",myname='xxx',ylabel='产量')  # 每次调用只在一个子图中绘图
draw_a(ax2,df,x_col=0,y_cols=[2,6],title="2001-2021年粮食、油料增长率走势折线图",myname='xxx',ylabel='增长率')  # 每次调用只在一个子图中绘图
plt.tight_layout()

We explain the code of this experiment from top to bottom.

(1) Canvas Settings

f,(ax1,ax2) = plt.subplots(2,1,figsize=(6,6),dpi=100)

It is used to create the total canvas/figure "window". With a figure, you can draw on it (or one of the subgrids/subplots). (fig: is the abbreviation of figure)

The previous 2,1 is to create a sub-graph with two rows and one column, which is equivalent to two graphs placed vertically.

figsize=(6,6): Canvas size 6*6

dpi=100: pixels of the canvas

Here we want to draw two pictures, so ax1 and ax2 are used in front of the canvas setting, f is the meaning of the figure window, and ax1 and ax2 are data parameters.

(2) Function incoming parameter setting

draw_a is the name of the established function, which can be defined according to one's own choice, and the description of the incoming parameters is in the brackets, which can be changed by oneself when citing.

ax: pass in canvas parameters

df: incoming data parameters

x_col: The x-axis index parameter is also the parameter required for data filtering. It is used here to select the X-axis data. It can be seen from the figure below that its filtering is in the form of column index, not including the column name

y_cols: y-axis index parameter, where each graph has two sets of data, which is a combination of two sets of data, so it is in the form of [1,5] when calling.

 colors, mark: the color and shape of the graphic lines

title: graphic title

myname: personal information label

ylabel: y-axis label name, because the x-axis labels are the same, so only the y-axis label is set

(3) Interpretation of the internal code of the function

① Filter data

Filter out the data of the X, Y axis data

X = df.iloc[:,x_col] # Series
Y = df.iloc[:,y_cols]

②Set X-axis, Y-axis label, title

title = "【"+myname+"】" + title
xlabel = "【"+myname+"】" + df.columns[x_col]
ylabel = "【"+myname+"】" + ylabel

③Cycle transfers the data parameters to the canvas subgraph

The data is passed in through the ax.plot function, and the ax.set_ setting part is used to pass the parameters to be set into the function, where the ax.set_xticklabels() function is to set the style of the x and y axis scales, rotation is the rotation degree of the scale value, and fontsize is Scale size setting, ax.get_yticks() returns the y scale as a list of positions, ax.legend() is to set the legend

    for i in Y.columns:
        ax.plot(X,Y[i],label=i)
        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)
        ax.set_xticklabels(X,rotation=90,fontsize=8)
        ax.set_yticklabels(ax.get_yticks(),fontsize=8)
        ax.set_title(title)
        ax.legend()

(4) Function call

By directly using draw_a (parameter value): here the parameter does not set the initial value must pass in the parameter, the parameter for setting the initial value can be passed in or not, this is the use of custom functions in Python and the use of parameter variables question.

(5) Use of plt.tight_layout() function

" tight_layout will automatically adjust the subplot parameters to fill the entire image area. This is an experimental feature and may not work in some cases. It only checks the axis labels, tick labels and title parts. When you have multiple subplots , you will often see labels for different axes stacked together.

(6) Finally, the graphics are made as follows

(Code words are not easy to click to pay attention not to get lost)

(Article questions, personal questions private messages)

Guess you like

Origin blog.csdn.net/Sheenky/article/details/124662362