matplotlib.pyplot教程

这篇教程主要介绍了matplotlib.pyplot的使用,包括控制线属性、处理多个图形和坐标轴、文本操作,如数学公式和注释,以及对数和其他非线性坐标轴的使用。教程通过实例解释了如何创建和自定义图形,例如设置线宽、颜色和风格,以及如何创建子图和自定义坐标轴范围。
摘要由CSDN通过智能技术生成

写在前面,本教程主要参考matplotlib.pyplot的官方教程,并对部分进行自己的理解和标注。
同时本教程也算是自己学习过程的一个记录和笔记。喜者自取,不喜勿喷

Pyplot tutorial

matplotlib.pyplot is a collection of command style functions that make matplotlib work like MATLAB. Each pyplot function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc. In matplotlib.pyplot various states are preserved across function calls, so that it keeps track of things like the current figure and plotting area, and the plotting functions are directed to the current axes (please note that “axes” here and in most places in the documentation refers to the axes part of a figure and not the strict mathematical term for more than one axis).

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('Y_lable')
plt.show()

在这里插入图片描述

You may be wondering why the x-axis ranges from 0-3 and the y-axis from 1-4. If you provide a single list or array to the plot() command, matplotlib assumes it is a sequence of y values, and automatically generates the x values for you. Since python ranges start with 0, the default x vector has the same length as y but starts with 0. Hence the x data are [0,1,2,3].

plot() is a versatile command, and will take an arbitrary number of arguments. For example, to plot x versus y, you can issue the command:

plt.plot([1,2,3,4],[8,3,2,5])

在这里插入图片描述
For every x, y pair of arguments, there is an optional third argument which is the format string that indicates the color and line type of the plot. The letters and symbols of the format string are from MATLAB, and you concatenate a color string with a line style string. The default format string is ‘b-‘, which is a solid blue line. For example, to plot the above with red circles, you would issue

plt.plot([1,2,3,4],[8,3,2,6],'ro')
plt.axis([0,10,0,10]) #每个坐标轴的范围

在这里插入图片描述
See the plot() documentation for a complete list of line styles and format strings. The axis() command in the example above takes a list of [xmin, xmax, ymin, ymax] and specifies the viewport of the axes.

If matplotlib were limited to working with lists, it would be fairly useless for numeric processing. Generally, you will use numpy arrays. In fact, all sequences are converted to numpy arrays internally. The example below illustrates a plotting several lines with different format styles in one command using arrays.

import matplotlib.pyplot as plt
import numpy as np
t=np.arange(0,5,0.5)
plt.plot(t,5*t,'r-',t,t**3,'bo',t,np.sqrt(t),'g^')

在这里插入图片描述

Controlling line properties

Lines have many attributes that you can set: linewidth, dash style, antialiased, etc; see matplotlib.lines.Line2D. There are several ways to set line properties

  • Use keyword args:
plt.plot(t,t**3,linewidth=5)

在这里插入图片描述

  • Use the setter methods of a Line2D instance. plot returns a list of Line2D objects; e.g., line1, line2 = plot(x1, y1, x2, y2). In the code below we will suppose that we have only one line so that the list returned is of length 1. We use tuple unpacking with line, to get the first element of that list:
line, = plt.plot(t, t**3, '-',linewidth=6)
line.set_antialiased(False) # turn off antialising 关闭抗锯齿

在这里插入图片描述

  • Use the setp() command. The example below uses a MATLAB-style command to set multiple properties on a list of lines. setp works transparently with a list of objects or a single object. You can either use python keyword arguments or MATLAB-style string/value pairs:
lines=plt.plot(t,t**3,t,20*t)
plt.setp(lines,color='r',linewidth=5)

在这里插入图片描述
Here are the available Line2D properties.

PropertyValue Type
alphafloat
animated[True False]
antialiased or aa[True False]
clip_boxa matplotlib.transform.Bbox instance
clip_on[True False]
clip_patha Path instance and a Transform instance, a Patch
color or cany matplotlib color
containsthe hit testing function
dash_capstyle[‘butt’ ‘round’ ‘projecting’]
dash_joinstyle[‘miter’ ‘round’ ‘bevel’]
dashessequence of on/off ink in points
data(np.array xdata, np.array ydata)
figurea matplotlib.figure.Figure instance
labelany string
linestyle or ls[ ‘-’ , ‘–’ ,’-.’ , ‘:’ ,‘steps’ , …]
linewidth or lwfloat value in points
lod[True False]
marker[ ‘+’ , ‘,’ , ‘.’ , ‘1’ , ‘2’ , ‘3’ , ‘4’ ]
markeredgecolor or mecany matplotlib color
markeredgewidth or mewfloat value in points
markerfacecolor or mfcany matplotlib color
markersize or msfloat
markevery[ None , integer , (startind, stride) ]
pickerused in interactive line selection
pickradiusthe line pick selection radius
solid_capstyle[‘butt’ , ‘round’ , ‘projecting’]
solid_joinstyle[‘miter’ , ‘round’ , ‘bevel’]
transforma matplotlib.transforms.Transform instance
visible[True , False]
xdatanp.array
ydatanp.array
zorderany number

To get a list of settable line properties, call the setp() function with a line or lines as argument

lines=plt.plot(t,t**3,t,20*t)
plt.setp(lines)
 agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array 
  alpha: float (0.0 transparent through 1.0 opaque) 
  animated: bool 
  antialiased or aa: bool 
  clip_box: a `.Bbox` instance 
  clip_on: bool 
  clip_path: [(`~matplotlib.path.Path`, `.Transform`) | `.Patch` | None] 
  color or c: any matplotlib color 
  contains: a callable function 
  dash_capstyle: ['butt' | 'round' | 'projecting'] 
  dash_joinstyle: ['miter' | 'round' | 'bevel'] 
  dashes: sequence of on/off ink in points 
  drawstyle: ['default' | 'steps' | 'steps-pre' | 'steps-mid' | 'steps-post'] 
  figure: a `.Figure` instance 
  fillstyle: ['full' | 'left' | 'right' | 'bottom' | 'top' | 'none'] 
  gid: an id string 
  label: object 
  linestyle or ls: ['solid' | 'dashed', 'dashdot', 'dotted' | (offset, on-off-dash-seq) | ``'-'`` | ``'--'`` | ``'-.'`` | ``':'`` | ``'None'`` | ``' '`` | ``''``]
  linewidth or lw: float value in points 
  marker: :mod:`A valid marker style <matplotlib.markers>`
  markeredgecolor or mec: any matplotlib color 
  markeredgewidth or mew: float value in points 
  markerfacecolor or mfc: any matplotlib color 
  markerfacecoloralt or mfcalt: any matplotlib color 
  markersize or ms: float 
  markevery: [None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]
  path_effects: `.AbstractPathEffect` 
  picker: float distance in points or callable pick function ``fn(artist, event)`` 
  pickradius: float distance in points
  rasterized: bool or None 
  sketch_params: (scale: float, length: float, randomness: float) 
  snap: bool or None 
  solid_capstyle: ['butt' | 'round' |  'projecting'] 
  solid_joinstyle: ['miter' | 'round' | 'bevel'] 
  transform: a :class:`matplotlib.transforms.Transform` instance 
  url: a url string 
  visible: bool 
  xdata: 1D array 
  ydata: 1D array 
  zorder: float 

在这里插入图片描述

Working with multiple figures and axes

MATLAB, and pyplot, have the concept of the current figure and the current axes. All plotting commands apply to the current axes. The function gca() returns the current axes (a matplotlib.axes.Axes instance), and gcf() returns the current figure (matplotlib.figure.Figure instance). Normally, you don’t have to worry about this, because it is all taken care of behind the scenes. Below is a script to create two subplots.

import numpy as np
import matplotlib.pyplot as plt

def f(t):
    return np.exp(-t) * np.cos(2*np.pi*t)
t1=np.arange(0,5,0.05)
t2=np.arange(0,10,0.1)
plt.figure(1)
plt.subplot(121)
plt.plot(t1,f(t1),'r-',t1,np.sqrt(t1),'go')
plt.subplot(122)
plt.plot(t1,np.cos(t1),'b--',t2,t2,t2,np.cos(t2))

在这里插入图片描述

import numpy as np
import matplotlib.pyplot as plt

def f(t):
    return np.exp(-t) * np.cos(2*np.pi*t)
t1=np.arange(0,5,0.05)
t2=np.arange(0,10,0.1)
plt.figure(1)
plt.subplot(211)
plt.plot(t1,f(t1),'r-',t1,np.sqrt(t1),'go')
plt.subplot(212)
plt.plot(t1,np.sin(t1),'b--',t2,t2,t2,np.cos(t2))

在这里插入图片描述
The figure() command here is optional because figure(1) will be created by default, just as a subplot(111) will be created by default if you don’t manually specify any axes. The subplot() command specifies numrows, numcols, fignum where fignum ranges from 1 to numrows*numcols. The commas in the subplot command are optional if numrows*numcols<10. So subplot(211) is identical to subplot(2, 1, 1). You can create an arbitrary number of subplots and axes. If you want to place an axes manually, i.e., not on a rectangular grid, use the axes() command, which allows you to specify the location as axes([left, bottom, width, height]) where all values are in fractional (0 to 1) coordinates. See pylab_examplesexample code: axes_demo.py for an example of placing axes manually and pylab_examples example code: subplots_demo.py for an example with lots of subplots.

You can create multiple figures by using multiple figure() calls with an increasing figure number. Of course, each figure can contain as many axes and subplots as your heart desires:

import matplotlib.pyplot as plt
plt.figure(1)                # the first figure
plt.subplot(211)             # the first subplot in the first figure
plt.plot([1, 2, 3])
plt.subplot(212)             # the second subplot in the first figure
plt.plot([4, 5, 6])


plt.figure(2)                # a second figure
plt.plot([4, 5, 6])          # creates a subplot(111) by default

plt.figure(1)                # figure 1 current; subplot(212) still current
plt.subplot(211)             # make subplot(211) in figure1 current
plt.title('Easy as 1, 2, 3') # subplot 211 title

在这里插入图片描述

MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.

You can clear the current figure with clf() and the current axes with cla(). If you find it annoying that states (specifically the current image, figure and axes) are being maintained for you behind the scenes, don’t despair: this is just a thin stateful wrapper around an object oriented API, which you can use instead (see Artist tutorial)

If you are making lots of figures, you need to be aware of one more thing: the memory required for a figure is not completely released until the figure is explicitly closed with close(). Deleting all references to the figure, and/or using the window manager to kill the window in which the figure appears on the screen, is not enough, because pyplot maintains internal references until close() is called.

Working with text

The text() command can be used to add text in an arbitrary location, and the xlabel(), ylabel() and title() are used to add text in the indicated locations (see Text introduction for a more detailed example)

np.random.seed(9999)
mu,sigma=100,15
x=mu+sigma*np.random.randn(1000)
n,bias,patches=plt.hist(x,30,density=1,facecolor='b',alpha=0.75)
plt.xlabel('Smarts') #x轴标注
plt.ylabel('Probability')#y轴标注
plt.title('Histogram of IQ')# 图题目
plt.text(60,.025,r'$\mu=100,\ \sigma=15$') #插入文档,60,。025是坐标,后面是字符串
plt.axis([40,160,0,0.03]) #x,y轴的取值范围
plt.grid(True) #是否显示网格
#plt.show()

UserWarning: The ‘normed’ kwarg is deprecated, and has been replaced by the ‘density’ kwarg.

在这里插入图片描述
All of the text() commands return an matplotlib.text.Text instance. Just as with with lines above, you can customize the properties by passing keyword arguments into the text functions or using setp():

t = plt.xlabel('my data', fontsize=14, color='red')

These properties are covered in more detail in Text properties and layout.

Using mathematical expressions in text

matplotlib accepts TeX equation expressions in any text expression σ i = 15 \sigma_i=15 σi=15. For example to write the expression in the title, you can write a TeX expression surrounded by dollar signs:

plt.title(r'$\sigma_i=15$')

The r r r preceding the title string is important – it signifies that the string is a raw string and not to treat backslashes as python escapes. matplotlib has a built-in TeX expression parser and layout engine, and ships its own math fonts – for details see Writing mathematical expressions. Thus you can use mathematical text across platforms without requiring a TeX installation. For those who have LaTeX and dvipng installed, you can also use LaTeX to format your text and incorporate the output directly into your display figures or saved postscript – see Text rendering With LaTeX.(python中r好像叫做非转义字符,简单来说就是r后面的字符串全是raw字符串,LaTex就是一种表达数学公式的语法,挺有用的。)

Annotating text

The uses of the basic text() command above place text at an arbitrary position on the Axes. A common use for text is to annotate some feature of the plot, and the annotate() method provides helper functionality to make annotations easy. In an annotation, there are two points to consider: the location being annotated represented by the argument xy and the location of the text xytext. Both of these arguments are (x,y) tuples.

ax=plt.subplot(111)
t=np.arange(0,5,0.01)
s=np.cos(2*np.pi*t)
lins,=plt.plot(t,s,'g--',lw=2)
plt.annotate('lins',xy=(2,0),xytext=(3,1.5),arrowprops=dict(facecolor='black',shrink=0.01))
plt.ylim(-2,2)

在这里插入图片描述
In this basic example, both the xy (arrow tip) and xytext locations (text location) are in data coordinates. There are a variety of other coordinate systems one can choose – see Basic annotation and Advanced Annotation for details. More examples can be found in pylab_examples example code: annotation_demo.py.

Logarithmic and other nonlinear axes

matplotlib.pyplot supports not only linear axis scales, but also logarithmic and logit scales. This is commonly used if data spans many orders of magnitude. Changing the scale of an axis is easy:

plt.xscale(‘log’)

An example of four plots with the same data and different scales for the y axis is shown below.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter
np.random.seed(19680801)
y=np.random.normal(loc=0.5,scale=0.4,size=1000)
y=y[(y>0)&(y<1)]
y.sort()
x=np.arange(len(y))
#linear
plt.subplot(221)
plt.plot(x,y)
plt.title('Linear')
plt.grid(True)
#log
plt.subplot(222)
plt.plot(x,y)
plt.yscale('log')
plt.title('Log')
plt.grid()
#symmetric log
plt.subplot(223)
plt.plot(x,y)
plt.yscale('symlog',linthreshy=0.05) #这里的Log,symlog 等是关键词
plt.title('symlog')
plt.grid()
#logit
plt.subplot(224)
plt.plot(x,y)
plt.yscale('logit') #这里的Log,symlog 等是关键词
plt.title('symlog')
plt.grid()
plt.gca().yaxis.set_minor_formatter(NullFormatter())
plt.subplots_adjust(top=0,bottom=-2,left=-2,right=0,hspace=0.25,wspace=0.25)

在这里插入图片描述
It is also possible to add your own scale, see Developer’s guide for creating scales and transformations for details.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值