Backend Development
Python Tutorial
Teach you step by step how to use the plot() function to draw pictures in PythonTeach you step by step how to use the plot() function to draw pictures in Python
This article brings you relevant knowledge about python, which mainly introduces related issues about using the plot() function to draw pictures, including the basic understanding and use of this function, as well as the Let’s take a look at the function data visualization drawings and basic parameter settings. I hope it will be helpful to everyone.

Recommended learning: python video tutorial
1. Understanding the plot() function
When using Python In data visualization programming, the matplotlib library is a commonly used 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 study of the matplotlib library.
Directly use the plot() function to draw graphs, which is for general simple data. We can directly draw the list data by calling the plot() function directly. Directly using the plot() function in initial learning can help us lay the parameters and foundation of the function for subsequent graphics learning.
Matplotlib graph composition:
- Figure (canvas)
- Axes (coordinate system)
- Axis (coordinate axis)
- Graphics (plot(), scatter(), bar(),...)
- Title, Labels, ......
Use plot() directly ) The function drawing method is as follows:
plt.plot(x, y, fmt='xxx', linestyle=, marker=, color=, linewidth=, markersize=, label=, )
where x, y represent the 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 parameter | Line shape |
| solid line | |
| Dotted line | |
| Dotted line | |
| Dotted line | |
| wireless |
(3) marker: point style, string
marker (point style)| Marker point | |
| 店 | ## ',' |
| ##'^' 'v' '>' ' | |
| '1' '2' '3' '4' | |
| 'o' | |
| 's' 'D' | |
| 'p' | |
| 'h' 'H' | |
| '*' | |
| ' ' 'x' | |
| '_' | |
| ' | |
| ##(4) markersize: the size of the point, parameter form: numerical value |
color (point, line color)
| 'r' | 红 |
| 'g' | Green |
| ##'b' | Blue |
| 'y' | Yellow |
| 'c' | 青 |
| 'm' | 品 |
| 'k' | 黑 |
| 'w' | 白 |
|
此处颜色参数还可以有二进制,十进制等表示方法,同时对于颜色,RGB是三原色 (6)label:图例,legend文字 二、plot()函数基本运用使用plot()函数时需要导入对应的库,导入库后我们在未有数据的情况下直接画图,直接画图会隐式创建Figure,Axes对象。 import matplotlib.pyplot as plt plt.plot()
下面通过构造数据绘制简单图形 首先数据构造,设置参数,参数也可以在将数据填入plot()函数的时候设置。 # 导入包 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 画出图形 # 生成一个Figure画布和一个Axes坐标系 fig, ax = plt.subplots() # 在生成的坐标系下画折线图 ax.plot(x, y, c, linewidth=lw) # 显示图形 plt.show() 图形展示:
给定两组数据,建立y与x的关系试,使用plot函数进行画图,本次画图线条选用点虚线形式,粗细选用1,点选用方形,点大小选用值为10,图例为‘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() 作出图片如下;
下面我们引用numpy的linspace函数生创建均匀分布序列,然后对x,y建立数值关系,由此来创建图画。 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') 作出如下图案,由此可见,我们对于图形的设置方面,在我们熟练以后如果没有粗细的设置可以直接缩减再一个字符串里面
以上都是简单图形的讲解,我们现在通过一个简单的对数据DataFrame进行作图,在往后的数据可视化中我们需要对数据进行处理后再进行可视化。下面我们通过正、余弦函数进行作图。 #导入包 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() 我们通过numpy的linspace方法生成数据再通过pandas对数据进行DataFrame化再带入plot()函数,此处需要讲的就是图例的命名方法,通过在函数中写入label参数,确定图例的标签,再通过legend()函数生成图例,在后续的学习中也会讲到图例的位置、形式等的运用。
三、plot()函数数据可视化画图以及图元基本参数设置通过绘制世界人口变化曲线图了解基本图元参数设置,本次绘图过程主要是先通过对人口数据导入,了解数据构造,再进配置画图参数最后完成图形的制作,其中基本的图元参数用于别的图形也适用,在这儿学会了我们只需要了解数据结构,构造成图形所要的数据结构就可以就行画出自己想要的图形。 首先进行数据导入,了解数据结构形式。为了学习方便,选用jupyter notebook进行可视化图形讲解。 import pandas as pd datafile = r'world_population.txt' # 打开文件 df = pd.read_csv(datafile) #读取数据 df.head()#展示前面部分数据 以下就是基本的数据样式,由年份和人口数量组成
这里做了基本的图元设计,也就是对于画布的设置,前面我们所学函数参数都是对于图形中间的设置,我们构成一个可视化界面是通过画布+画中图形样式组成一个完整的可视化界面。 画布界面有画布大小,画布像素,画布界面,画布边框等设置。 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")
构成一个完整的可视化图像除了图例还有图像的标题,我们可以通过title()方法设置英文标题,中文标题要通过以下代码才能实现,因此我们如果是做中文项目在导入包以后就可以写上设置中文代码的代码串。 # 设置中文字体 plt.rcParams['font.sans-serif'] = 'SimHei' # 设置字体为简黑(SimHei) plt.rcParams['font.sans-serif'] = 'FangSong' # 设置字体为仿宋(FangSong)
当然,除了这种比较简单的图形之外我们还能对图形进行优化设置,将数据显示的更加的精美和美观,对图形优化便于实际报告中的演示也是我们现在必不可少的的一环。 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'
上述代码,对x轴,y轴的刻度、标签、字体进行定义,对图例、网格线等也做出了参数的设置,最后做出的图形如下图:
推荐学习:python视频教程 |
The above is the detailed content of Teach you step by step how to use the plot() function to draw pictures in Python. For more information, please follow other related articles on the PHP Chinese website!
Python: Automation, Scripting, and Task ManagementApr 16, 2025 am 12:14 AMPython excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.
Python and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AMTo maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.
Python: Games, GUIs, and MoreApr 13, 2025 am 12:14 AMPython excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.
Python vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AMPython is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.
The 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AMYou can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.
Python: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AMPython is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.
How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PMYou can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.
How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AMHow to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version
Recommended: Win version, supports code prompts!

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),















