当前位置:网站首页>Data visualization: plotting sine and cosine curves with Matplotlib
Data visualization: plotting sine and cosine curves with Matplotlib
2022-07-18 18:01:00 【Lan Zhou Qianfan】
preface :
stay python Inside , Data visualization is python A highlight of . stay python Inside , What effect can data visualization achieve , This is of course related to the library we use .python You often need to import libraries , And keep calling methods , It's like a stream data visualization Library , There's a lot of , Many can be developed later , Then we call . Read about pyecharts Beautiful visual interface , take pyecharts and matplotlib Compare .
pyecharts and matplotlib What's the difference ?Matplotlib yes Python The leader of data visualization Library , Although it has a history of more than ten years , But it's still Python The most widely used Gallery in the community , Its design and MATLAB Very similar , Provides a complete set and MATLAB Similar orders API, Suitable for interactive mapping , You can also use it as a drawing control , Embed in other applications . Pyecharts It's a will Python And Echarts A combined data visualization tool , It can be configured with high flexibility , Easily match with beautiful views . among Echarts Baidu is an open source data visualization library , and Pyecharts take Echarts And Python Organic docking , Convenient in Python Directly generate all kinds of beautiful graphics .
Data visualization matplotlib Draw a sine cosine curve
Let's first look at the final effect
The picture above is the final saved picture view effect We do it step by step 1: First, we need to import the basic library matplotlib numpy matplotlib This is the library we need in this chapter numpy It is a common library for our data analysis and processing , It is also often used in machine learning .
Step by step Here are some Inline code slice .
First step
#1: Methods and parameters used
# linspace(start, stop, num=50, endpoint=True,
# retstep=False, dtype=None)
# Description of relevant parameters
# Specified in the start To stop Mean value
# start: Do not omit
# stop: Sometimes it includes, sometimes it doesn't , according to endpoint Choose , Default includes
# num: Specify the number of equal points , The default is 50
# endpoint: Boolean value , Optional , The default is True. contain stop Just True, If it doesn't include # False
# retstep : Boolean value , Optional , The default is False. If True, Return value and step size
# dtype : Output data type , Optional . If you don't specify , According to the data type of the previous parameter
# 2:np.plot(x,y,color,lw,label,ms,mk,mec,mfc)
# among X By the coordinates of all input points x The value of ,Y It's by and by X It contains x Corresponding y Group
# Into a vector
# color Specifies the color of the line
# lw Specify the width of the line
# lw Specifies the style of the line , The default is to implement
# mk You can specify a data identifier
# ms You can specify the size of the identifier
# mec You can specify the boundary color of the identifier
# mfc The internal fill color of the identifier import matplotlib.pyplot as plt
import numpy as np
# For normal display of Chinese labels
plt.rcParams['font.sans-serif']=['SimHei']
# Used to display symbols normally
plt.rcParams['axes.unicode_minus']=False
x = np.linspace(-np.pi,np.pi,256,endpoint = 256)
sin,cos = np.sin(x),np.cos(x)
# draw , And set the relevant parameters , The label will not be displayed here , Because there is not yet
# Add legend , Look down
plt.plot(x,sin,color = 'blue',lw=2.5,label = ' sine sin',mec='red')
plt.plot(x,cos,color = 'red',lw = 2.5,label = ' cosine cos()')
plt.show() # Show The second step
# Methods and parameters used
# plt.xlim(xmin, xmax)
# xmin:x The minimum value on the axis
# xmax:x The maximum value on the axis
#plt.ylim() The same reason as above
# How to use it , You can see the following example code plt.xlim(x.min()*1.5,x.max()*1.5) # take x Axis stretch 1.5 times
plt.ylim(cos.min()*1.5,cos.max()*1.5) # take y Axis stretch 1.5 times
plt.show()The third step
# The methods and parameters used
# plt.xticks([],[])
# plt.yticks([],[])
# plt.title('',color,color,..) # Set title , The relevant parameters inside can # Appoint
# plt.text( Remarks x Axis coordinates , Remarks y Axis coordinates ,' Remarks ',fontsize,color,..) # Add notes to the bottom right corner
# What I want to say is that there are even two parameters , Show them in the form of a list .
Now we only need to introduce the method used to set the coordinate scale . The second parameter list
Is used to escape . Examples are as follows . Here are some Inline code slice .
stay x On the scale of the shaft , We need to use regular sine and cosine scales to , Instead of simple real numbers , We need pi . So in plt.xticks([],[]) Need to escape on the second list parameter of .
# there r’ The representative starts , For the end ,\ It stands for escape ,\pi It stands for pi ,r Represents the original string . Therefore, they can correspond one by one .
plt.xticks([-np.pi,-np.pi/2,0,np.pi/2,np.pi],
[r'$-\pi$',r'$-\pi/2$',r'$0$',r'$\pi/2$',r'$\pi$'])
plt.yticks([-1,0,1])
plt.title(" Plot sine and cosine function curve ",fontsize = 16,color ='green')
# Add a note label to the bottom right corner of the picture
plt.text(+2.2,-1.4,"by:jgdabc",fontsize=16,color = 'purple')
plt.show()Step four :
Methods and parameters used :
plt.gca()# This method has something .
I want to simply understand ,Python The library is too complicated . There is a big nod .
plt.gca(), You can get axes object
What is axes object ?
stay matplotlib in , The whole chart is one figure object . Every figure
An object can contain one or more axes, and axes For the axis . Every axes
An object is a drawing area with its own coordinate system . We can understand it as through
In this way, we can get axes object , And this object can help us
Convenient operation coordinate axis ,ok. See examples for specific operations !# I believe those who can understand English can understand without reading the notes
ax = plt.gca() # obtain Axes object
ax.spines['right'].set_color('none') # Hide right border
ax.spines['top'].set_color('none')# Hide the upper boundary
ax.xaxis.set_ticks_position('bottom') #x The axis coordinate scale is set below the coordinates
ax.spines['bottom'].set_position(('data',0))# take x The axis translation passes through (0,0) The location of
ax.yaxis.set_ticks_position('left')# take y The axis coordinate scale is set to the left of the coordinate axis
ax.spines['left'].set_position(('data',0))# take y Axis translation to (0,0) Location
plt.show()Are the brothers a little alike , Is not enough .
Step five :
Methods and parameters used :
plt.legend()
Add legend
This will put me above label Show the content of .plt.legend(loc ='upper left',fontsize=12)
plt.show()Step six Pay attention to step 6. We need to describe , And draw lines
Methods and parameters used
plt.plot() # This has been explained earlier , I won't repeat , Here we are
To add a parameter linewidth Appoint , Change it to a dotted line
plt.scatter() # Used to draw the position of two points
plt.annotate # Used to add annotation text , The specific explanation is explained in the example code
```javascript
t1 = 2*np.pi/3 # Take a x Axis coordinate point
t2 = -np.pi # Take the second coordinate point
# Draw lines according to , The first list is x Axis coordinate value , The second list is y Axis coordinate value
plt.plot([t1,t1],[0,np.sin(t1)],color = 'b',linewidth = 1.5,linestyle = '--')
# Draw line
plt.plot([t2,t2],[0,np.cos(t2)],color ='r',linewidth=1.5,linestyle="--")
# Mark the position of the two points ( How to draw a scatter diagram )
plt.scatter([t1,],[np.sin(t1),],50,color = 'b') #50 For the specified size
# Add notes to the chart
plt.scatter([t2,],[np.cos(t2),],50,color = 'r')
plt.annotate( r'$\sin(\frac{2\pi}{3}=\frac{\sqrt{3}}{2}$)',
xy = (t1,np.sin(t1)), # Location of points
xycoords = 'data', # The offset of the annotation text
xytext = (+10,+30), # The horizontal and vertical distance of the text from the point
textcoords = 'offset points',
fontsize =14,# The size of the comment
arrowprops = dict(arrowstyle = '->',connectionstyle = 'arc3,rad=.2')# The curvature pointed by the arrow
)
plt.annotate(r'$\cos(-\pi)=-1$',
xy = (t2,np.cos(t2)),
xycoords = 'data', # The offset of the annotation text
xytext = (0 ,-40), # The horizontal and vertical distance of the text from the point
textcoords = 'offset points',
fontsize = 14,# The size of the comment
arrowprops = dict(arrowstyle = '->',connectionstyle='arc3,rad=.2')
) # Location of points
plt.show()Step seven : I want to set up x Axis and y Axis font , When it comes to shafts , Just use ax. Let's go straight to the code to explain
# Traversal access x Axis and y Axis scale , And set the font
for label in ax.get_xticklabels() + ax.get_yticklabels() :
label.set_fontsize(18)
label.set_bbox(dict(facecolor = 'r',edgecolor='g',alpha=0.5))#alpha On behalf of transparency
# Draw the fill area
plt.fill_between(x,np.abs(x)<0.5,sin,sin>0.5,color='g',alpha =0.8)
plt.fill_between(x,cos,where = (-2.5<x)&(x<-0.5),color = 'purple')
plt.grid() # Draw gridlines
plt.savefig("D:\python Learn data visualization matplot Study .png",dpi = 300) Save the picture
plt.show()Note that you must save here first , after show.
Final effect
Give you the complete code
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False
x = np.linspace(-np.pi,np.pi,256,endpoint=256)
sin,cos = np.sin(x),np.cos(x)
plt.plot(x,sin,color = 'blue',lw=2.5,label = ' sine sin',mec='red')
plt.plot(x,cos,color = 'red',lw = 2.5,label = ' cosine cos()')
plt.xlim(x.min()*1.5,x.max()*1.5)
plt.ylim(cos.min()*1.5,cos.max()*1.5)
plt.xticks([-np.pi,-np.pi/2,0,np.pi/2,np.pi],[r'$-\pi$',r'$-\pi/2$',r'$0$',r'$\pi/2$',r'$\pi$'])
plt.yticks([-1,0,1])
plt.title(" Plot sine and cosine function curve ",fontsize = 16,color ='green')
plt.text(+2.2,-1.4,"by:jgdabc",fontsize=16,color = 'purple')
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
plt.legend(loc ='upper left',fontsize=12)
t1 = 2*np.pi/3
t2 = -np.pi
plt.plot([t1,t1],[0,np.sin(t1)],color = 'b',linewidth = 1.5,linestyle = '--')
plt.plot([t2,t2],[0,np.cos(t2)],color ='r',linewidth=1.5,linestyle="--")
plt.scatter([t1,],[np.sin(t1),],50,color = 'b')
plt.scatter([t2,],[np.cos(2),],50,color = 'r')
plt.annotate( r'$\sin(\frac{2\pi}{3}=\frac{\sqrt{3}}{2}$)',
xy = (t1,np.sin(t1)),
xycoords = 'data',
xytext = (+10,+30),
textcoords = 'offset points',
fontsize =14,
arrowprops = dict(arrowstyle= '->',connectionstyle = 'arc3,rad=.2')# The curvature pointed by the arrow
)
plt.annotate(r'$\cos(-\pi)=-1$',
xy = (t2,np.cos(t2)),
xycoords = 'data',
xytext = (0 ,-40),
textcoords = 'offset points',
fontsize = 14,
arrowprops = dict(arrowstyle = '->',connectionstyle='arc3,rad=.2')
)
for label in ax.get_xticklabels() + ax.get_yticklabels() :
label.set_fontsize(18)
label.set_bbox(dict(facecolor = 'r',edgecolor='g',alpha=0.5))
plt.fill_between(x,np.abs(x)<0.5,sin,sin>0.5,color='g',alpha =0.8)
plt.fill_between(x,cos,where = (-2.5<x)&(x<-0.5),color = 'purple')
plt.grid()
plt.savefig("D:\python Learn data visualization matplot Study .png",dpi = 300)
plt.show()I also learned it from the Internet , Many method parameters are searched by Baidu . It feels like there are a lot of things , These codes have been typed twice . But I still feel a little forgotten. I have to check the usage . knowledge has no limit . No drainage , Just summarize and share I hope we can make progress together . Please also observe csdn Blog Association
边栏推荐
- Export data with navicatpremium
- ASP.NET印刷行业印务管理系统,源码免费分享
- 2022-07-15 第五小组 修身课 学习笔记(every day)
- 队列的基本操作
- 【Leetcode】232. 用栈实现队列
- Resolved SQL_ ERROR_ INFO: “You have an error in your SQL syntax; check the manual that corresponds to your
- [动态规划]DP19 最长公共子序列(一)-中等
- (manual) [sqli labs46, 47] order by injection, error echo, post injection, number / character type
- Outdoor LED display has a clever way to deal with hot weather
- Introduction to C language (7)
猜你喜欢

uniapp微信小程序 选择聊天记录文件上传

ECCV 2022 | 适用于分类,检测,分割的生成式知识蒸馏开源

进程【详细总结】

2022 G3 boiler water treatment examination question bank and simulation examination

Tcp/ip protocol of network principle

协作进程【简单总结】

用NavicatPremium导出数据

Outdoor LED display has a clever way to deal with hot weather

Notes on deep learning - regularization, optimizer, linear regression, logistic regression
![[CVPR2019] On Stabilizing Generative Adversarial Training with Noise](/img/f9/c7c7a8b41b9af05bf4cd4e44754eb0.png)
[CVPR2019] On Stabilizing Generative Adversarial Training with Noise
随机推荐
许久未见,我又回来啦
【Renesas RA6M4开发板之I2C读取BMP180气压温度】
守护线程及应用场景
27-Scala入门、基本数据类型和方法与函数的介绍
T-无限的路
近期群友遇到的软件测试面试题分享
Resolved SQL_ ERROR_ INFO: “You have an error in your SQL syntax; check the manual that corresponds to your
2022 simulated 100 questions and simulated examination for the main principals of hazardous chemical business units
Given an integer array nums and a target value target, find the two integers whose sum is the target value in the array, and return their array subscripts.
Qt Creator调试模式断点不起作用 MinCW可以
2022年G3锅炉水处理考试题库及模拟考试
How to adjust and set win11 color temperature
协作进程【简单总结】
原生fetch请求简单封装
2. STM32F4 USB协议研究 - SD卡模拟U盘
暑期学习Matlab笔记
NoSQLAttack工具下载与使用
[I2C of Renesas ra6m4 development board reads bmp180 air pressure and temperature]
【技术碎片】基于指数扩散二分搜索的重名文件重命名后缀
任意组件间通信的两种方法