search
HomeBackend DevelopmentPython TutorialTeach 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.

Teach you step by step how to use the plot() function to draw pictures in Python

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

##'-'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 size of the specified value, parameter format: numerical value
linestyle (line style)
linestyle parameter Line shape

(3) marker: point style, string

marker (point style) marker'.'## ','pixelupper, lower, left and right triangleThe upper, lower, left and right three-pronged lines CircleSquareFive sides ShapeHexagonPentagon Starcrosshorizontal line' (5) color: adjust the color of lines and points, string, parameter form string
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)

Stringcolor'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!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

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),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.