search
HomeBackend DevelopmentPython TutorialIntroduction to the method of drawing using the drawing library in python

Introduction to the method of drawing using the drawing library in python

May 12, 2017 am 10:49 AM
matplotlibnumpypythonDrawing

Matplotlib is Python's most famous drawing library. This article shares with you examples of how to use matplotlib+numpy to draw a variety of drawings, including filled plots, scatter plots, and bar plots. , contour plots, bitmaps and 3D diagrams, friends in need can refer to them. Let’s take a look together.

Preface

matplotlib is Python’s most famous drawing library. It provides a set of commands similar to matlabAPI, very suitable for interactive mapping. This article will analyze several graphs supported in matplot and commonly used in analysis in the form of examples. These include fill plots, scatter plots, bar plots, contour plots, dot plots and 3D plots. Let’s take a look at the detailed introduction:

1. Filling diagram

Reference code


from matplotlib.pyplot import *
x=linspace(-3,3,100)
y1=np.sin(x)
y2=np.cos(x)
fill_between(x,y1,y2,where=(y1>=y2),color='red',alpha=0.25)
fill_between(x,y1,y2,where=(y<>y2),color=&#39;green&#39;,alpha=0.25)
plot(x,y1)
plot(x,y2)
show()

Brief analysis

The fill_betweenfunction is mainly used here. This function is easy to understand. It is to pass in the array of the x-axis and the two y-axis arrays that need to be filled; then pass in the filled range and use where= to determine the filled area. ; Finally, you can add fill color, transparency and other modified parameters.

Of course the fill_between function has more advanced usage, see fill_between usage or help documentation for details.

Rendering

## 2. Scatter plots

Reference code


from matplotlib.pyplot import *
n = 1024
X = np.random.normal(0,1,n)
Y = np.random.normal(0,1,n)
T = np.arctan2(Y,X)
scatter(X,Y, s=75, c=T, alpha=.5)
xlim(-1.5,1.5)
ylim(-1.5,1.5)
show()

Brief analysis

First introduce Numpy's

normal function, obviously, this is a function that generates a normal distribution. This function accepts three parameters, which represent the mean, standard deviation, and length of the generated array respectively. Very easy to remember.

Then there is the

arctan2 function. This function accepts two parameters, representing the y array and the x array respectively, and then returns the corresponding arctan(y/x) value. , the result is in radians.

Next, the

scatter method of drawing a scatter plot is used. First, of course, the x and y arrays are passed in, and then the s parameter represents scale, which is the size of the scatter points; the c parameter represents color , what I passed him was an array divided according to the angle, which corresponds to the color of each point (although I don’t know how it corresponds, but it seems to be a relative conversion based on other elements in the array, which is not important here. , anyway, just assign the same value to the same color); the last is the alpha parameter, which represents the transparency of the point.

As for the advanced usage of

scatter function, please refer to the official document scatter function or help document.

Finally just set the coordinate range.

Rendering

##3. Bar plots

Reference code

from matplotlib.pyplot import *
n = 12
X = np.arange(n)
Y1 = (1-X/float(n)) * np.random.uniform(0.5,1.0,n)
Y2 = (1-X/float(n)) * np.random.uniform(0.5,1.0,n)
bar(X, +Y1, facecolor=&#39;#9999ff&#39;, edgecolor=&#39;white&#39;)
bar(X, -Y2, facecolor=&#39;#ff9999&#39;, edgecolor=&#39;white&#39;)
for x,y in zip(X,Y1):
 text(x+0.4, y+0.05, &#39;%.2f&#39; % y, ha=&#39;center&#39;, va= &#39;bottom&#39;)
for x,y in zip(X,Y2):
 text(x+0.4, -y-0.05, &#39;%.2f&#39; % y, ha=&#39;center&#39;, va= &#39;top&#39;)
xlim(-.5,n)
xticks([])
ylim(-1.25,+1.25)
yticks([])
show()

Brief analysis

Be careful to do it manually Import the pylab package, otherwise bar will not be found. . .

First use numpy's

arange

function to generate an array of [0,1,2,…,n]. (You can also use linspace) Secondly, use numpy's

uniform

function to generate a uniformly distributed array, passing in three parameters representing the lower bound, upper bound and array length respectively. And use this array to generate the data that needs to be displayed. Then comes the use of the bar function. The basic usage is similar to the previous plot and scatter. The horizontal and vertical coordinates and some decorative parameters are passed in.

Then we need to use

for

loop to display numbers for the histogram: use python's zip function to pair X and Y1 and merge them Loop through to get the position of each data, and then use the text function to display a string at that position (pay attention to the detailed adjustment of the position). text passes in the horizontal and vertical coordinates, the string to be displayed, the ha parameter specifies the horizontal alignment, and the va parameter specifies the vertical alignment. Finally adjust the coordinate range and cancel the scale on the horizontal and vertical coordinates to keep it beautiful.

As for the specific usage of the

bar

function, please refer to the bar function usage or the help document.

Rendering

##4. Contour plots


Reference Code


from matplotlib.pyplot import *
def f(x,y):
 return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
n = 256
x = np.linspace(-3,3,n)
y = np.linspace(-3,3,n)
X,Y = np.meshgrid(x,y)
contourf(X, Y, f(X,Y), 8, alpha=.75, cmap=cm.hot)
C = contour(X, Y, f(X,Y), 8, colors=&#39;black&#39;, linewidth=.5)
clabel(C, inline=1, fontsize=10)
show()

简要分析

首先要明确等高线图是一个三维立体图,所以我们要建立一个二元函数f,值由两个参数控制,(注意,这两个参数都应该是矩阵)。

然后我们需要用numpy的meshgrid函数生成一个三维网格,即,x轴由第一个参数指定,y轴由第二个参数指定。并返回两个增维后的矩阵,今后就用这两个矩阵来生成图像。

接着就用到coutourf函数了,所谓contourf,大概就是contour fill的意思吧,只填充,不描边;这个函数主要是接受三个参数,分别是之前生成的x、y矩阵和函数值;接着是一个整数,大概就是表示等高线的密度了,有默认值;然后就是透明度和配色问题了,cmap的配色方案这里不多研究。

随后就是contour函数了,很明显,这个函数是用来描线的。用法可以类似的推出来,不解释了,需要注意的是他返回一个对象,这个对象一般要保留下来个供后续的加工细化。

最后就是用clabel函数来在等高线图上表示高度了,传入之前的那个contour对象;然后是inline属性,这个表示是否清除数字下面的那条线,为了美观当然是清除了,而且默认的也是1;再就是指定线的宽度了,不解释,。

效果图

五、点阵图

参考代码


from matplotlib.pyplot import *
def f(x,y):
 return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
n = 10
x = np.linspace(-3,3,3.5*n)
y = np.linspace(-3,3,3.0*n)
X,Y = np.meshgrid(x,y)
Z = f(X,Y)
imshow(Z,interpolation=&#39;nearest&#39;, cmap=&#39;bone&#39;, origin=&#39;lower&#39;)
colorbar(shrink=.92)
show()

简要分析

这段代码的目的就是将一个矩阵直接转换为一张像照片一样的图,完整的进行显示。

前面的代码就是生成一个矩阵Z,不作解释。

接着用到了imshow函数,传人Z就可以显示出一个二维的图像了,图像的颜色是根据元素的值进行的自适应调整,后面接了一些修饰性的参数,比如配色方案(cmap),零点位置(origin)。

最后用colorbar显示一个色条,可以不传参数,这里传进去shrink参数用来调节他的长度。

效果图

六、3D图

参考代码


import numpy as np
from pylab import *
from mpl_toolkits.mplot3d import Axes3D
fig = figure()
ax = Axes3D(fig)
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.hot)
ax.contourf(X, Y, Z, zdir=&#39;z&#39;, offset=-2, cmap=plt.cm.hot)
ax.set_zlim(-2,2)
show()

简要分析

有点麻烦,需要用到的时候再说吧,不过原理也很简单,跟等高线图类似,先画图再描线,最后设置高度,都是一回事。

效果图

总结

【相关推荐】

1. Python免费视频教程

2. Python基础入门教程

3. Python在数据科学中的应用

The above is the detailed content of Introduction to the method of drawing using the drawing library in python. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
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.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

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