Python directly uses the plot() function to draw pictures

Table of contents

First, the understanding of the plot() function

Second, the basic use of the plot() function

 3. Plot() function data visualization drawing and basic parameter setting of primitives


First, the understanding of the plot() function

In data visualization programming using Python, the matplotlib library is a third-party library that we use to draw data. It contains various functions, that is, different types of graphics. To use the functions in the matplotlib library, you need to understand the format of the data required by the function. This is also the focus of our learning matplotlib library.

Directly use the plot() function to draw pictures, which is for general simple data. We can directly draw the list data by directly calling the plot() function. Using the plot() function directly in the initial learning can facilitate us to lay the parameters and foundation of the function for later graphic learning.

The composition of a matplotlib figure:

  • Figure (canvas)
  • Axes (coordinate system)
  • Axis (coordinate axis)
  • graphics (plot(), scatter(), bar(), ...)
  • Title, Labels, ......

Directly use the plot() function to draw pictures as follows:

plt.plot(x, y, fmt='xxx', linestyle=, marker=, color=, linewidth=, markersize=, label=, )

Among them, x and y represent horizontal and vertical coordinates, and fmt = '#color#linestyle#marker' represents various parameters.

(1) linestyle: This field is the style of the line, parameter form: string

linestyle (line style)
linestyle parameter Linear
'-' solid line
'--' dotted line
'-.' Dotted line
':' dotted line
' ' wireless

(2) linewidth: This parameter is the thickness of the line, the thickness is related to the set value, parameter form: value

(3) marker: point style, string

marker (point style)
marker mark point
'.' shop
',' pixel
'^' 'v' '>' '<' up and down left and right triangle
'1' '2' '3' '4' Up, down, left, and right trident lines
'o' round
's' 'D' square
'p' pentagon
'h' 'H' hexagon
'*' Pentagram
'+' 'x' cross
'_' horizontal line
' '

(4) markersize: point size, parameter form: numeric value

(5) color: adjust the color of the line and point, string, parameter form string

color (point, line color)
string color
'r' red
'g' green
'b' blue
'y' yellow
'c' green
'm' product
'k' black
'w' white

Here, the color parameters can also have binary, decimal and other representation methods. At the same time, for color, RGB is the three primary colors

(6) label: legend, legend text

Second, the basic use of the plot() function

When using the plot() function, you need to import the corresponding library. After importing the library, we can draw directly without data. Direct drawing will implicitly create Figure and Axes objects.

import matplotlib.pyplot as plt
plt.plot()

 The following draws simple graphics by constructing data

First, construct the data and set the parameters. The parameters can also be set when filling the data into the plot() function.

# 导入包
import matplotlib.pyplot as plt
import numpy as np
# 构造数据
# 位置 (2维:x,y一一对应)
x = np.linspace(0, 2 * np.pi, 200)  # 从0到2pi的200个值
y = np.sin(x)                       # 从sin(0)到sin(2pi)的200个值
# 颜色(0维)
c = 'red'
c = 'r'
c = '#FF0000'
# 大小(0维): 线宽
lw = 1

draw graphics

# 生成一个Figure画布和一个Axes坐标系
fig, ax = plt.subplots()
# 在生成的坐标系下画折线图
ax.plot(x, y, c, linewidth=lw)
# 显示图形
plt.show()

Graphic display:

Given two sets of data, try to establish the relationship between y and x, and use the plot function to draw a picture. This time, the line drawn is in the form of a dotted line, the thickness is 1, the point is a square, the point size is 10, and the legend is '1234'

import matplotlib.pyplot as plt
x = [1,2,3]
y = [1,2,3]
y = x
plt.plot(x,y,linestyle=':', linewidth=1, marker='d', markersize=10, label='1234')
plt.legend()

Make a picture as follows;

 Below we refer to numpy's linspace function to create a uniform distribution sequence, and then establish a numerical relationship between x and y to create a picture.

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-100,100,10)
y = x**2 + 2*x +1
plt.plot(x,y,'g-.o')

Make the following pattern, it can be seen that in terms of graphics settings, after we are proficient, if there is no thickness setting, we can directly reduce it into a string

The above are the explanations of simple graphics. Now we use a simple data frame to draw a graph. In the future data visualization, we need to process the data and then visualize it. Next, we use the sine and cosine functions to make graphs.

#导入包
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

#使用linspace()方法构成数据
x = np.linspace(0, 2 * np.pi, 50)  # 
y1 = np.sin(x)
y2 = np.cos(x)
#转化数据形式
df = pd.DataFrame([x,y1,y2]).T
#对列重新命名
df.columns = ['x','sin(x)','cos(x)']
#数据写入图像,命名图例
plt.plot(df['x'],df['sin(x)'],label='sin(x)')
plt.plot(df['x'],df['cos(x)'],label='cos(x)')
plt.legend()

We generate data through the linspace method of numpy, then DataFrame the data through pandas, and then bring it into the plot() function. What we need to talk about here is the naming method of the legend. By writing the label parameter in the function, determine the label of the legend, and then The legend is generated through the legend() function, and the use of the position and form of the legend will also be discussed in the subsequent study.

 

 3. Plot() function data visualization drawing and basic parameter setting of primitives

Understand the basic graphic element parameter settings by drawing the world population change curve. This drawing process is mainly to first import the population data, understand the data structure, and then configure the drawing parameters and finally complete the graphics production. The basic graphic element parameters are used for Other graphics are also applicable. We learned here that we only need to understand the data structure and construct the data structure required by the graphics to draw the graphics we want.

First, import data to understand the data structure. For the convenience of learning, jupyter notebook is selected for visual graphic explanation.

import pandas as pd
datafile = r'world_population.txt'  # 打开文件
df = pd.read_csv(datafile)  #读取数据
df.head()#展示前面部分数据

The following is the basic data format, consisting of year and population

 The basic primitive design is done here, that is, the settings for the canvas. The function parameters we learned earlier are all for the settings in the middle of the graphics. We form a visual interface through the canvas + in-picture graphic style to form a complete visual interface.

The canvas interface has settings such as canvas size, canvas pixels, canvas interface, and canvas border.

import matplotlib.pyplot as plt
# 画布
fig = plt.figure(figsize=(6,4),  # inches
                 dpi=120, # dot-per-inch
                 facecolor='#BBBBBB',
                 frameon=True, # 画布边框
                )  
plt.plot(df['year'],df['population'])

# 标题
plt.title("1960-2009 World Population")

In addition to the legend and the title of the image to form a complete visual image, we can set the English title through the title() method, and the Chinese title can only be realized through the following code, so if we are doing a Chinese project, we can write the settings after importing the package The code string of the Chinese code.

# 设置中文字体
plt.rcParams['font.sans-serif'] = 'SimHei'  # 设置字体为简黑(SimHei)
plt.rcParams['font.sans-serif'] = 'FangSong'  # 设置字体为仿宋(FangSong)

 Of course, in addition to this relatively simple graph, we can also optimize the graph to display the data more beautifully and beautifully. Optimizing the graph to facilitate the presentation in the actual report is also an indispensable part of us now.

import matplotlib.pyplot as plt

# 设置中文字体
plt.rcParams['axes.unicode_minus'] = False    # 不使用中文减号
plt.rcParams['font.sans-serif'] = 'FangSong'  # 设置字体为仿宋(FangSong)

# 画布
fig = plt.figure(figsize=(6,4),  # inches
                 dpi=120, # dot-per-inch
                 facecolor='#BBBBBB',
                 frameon=True, # 画布边框
                )  
plt.plot(df['year'],df['population'],'b:o',label='人口数')

# 中文标题
plt.title("1960-2009 世界人口")

# 字体字典
font_dict=dict(fontsize=8,
              color='k',
              family='SimHei',
              weight='light',
              style='italic',
              )

# X轴标签
plt.xlabel("年份", loc='center', fontdict=font_dict)   # loc: 左中右 left center right

# Y轴标签
plt.ylabel("人口数",loc='top', fontdict=font_dict)  # loc: 上中下 top center bottom

# X轴范围
plt.xlim((2000,2010))  # X轴的起点和终点

# Y轴范围
plt.ylim(6e9,7e9) # Y轴的起点和终点

# X轴刻度
plt.xticks(np.arange(2000,2011))

# X轴刻度
plt.yticks(np.arange(6e9,7e9+1e8,1e8))

# 图例
plt.legend()
# plt.legend(labels=['人口'])

# 网格线
plt.grid(axis='y')  # axis: 'both','x','y'

 The above code defines the scale, label, and font of the x-axis and y-axis, and also sets parameters for the legend, grid lines, etc., and the final graph is as follows:

Guess you like

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