matplotlib 2D绘图基础
来源:互联网 发布:宁波java软件公司排名 编辑:程序博客网 时间:2024/06/05 11:56
Pyplot tutorial
Demo地址为:点击打开链接 一个简单的例子:1.
# -*- coding: utf-
8
-*-
2.
import
matplotlib.pyplot as plt
3.
plt.plot([
1
,
4
,
9
,
16
])
4.
plt.ylabel(
'some numbers'
)
5.
plt.show()
运行结果为:
我只指定了一组list参数,从图中可以看书,这组参数自动分配为了纵坐标,为什么会这样呢?
你可能想知道为什么X轴的范围是0-3。如果你提供一个单一的列表或数组的plot()命令,matplotlib假定这是一个序列的y值(这个例子是[1,4,9,16]所以因此在零处y值是1,x=1时y=4,x=2时y=9),并自动生成X值。因为Python范围从0开始,默认x向量从0开始并以1为步长自动得到X坐标。因此X的数据为[ 0, 1, 2, 3 ]。
plot()是一种通用的命令,并将采取任意数量的参数。默认X和Y的参数为list(实际上内部都是转化为数组numpy),并且长度相同,否则报错。
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
对于每一个X,Y参数对,有一个可选的第三个参数是表示颜色的和线型的格式字符串。格式字符串的字母和符号来源于MATLAB,你可以制定颜色和线型。默认的格式字符串为“b-”,这是一个蓝线实线。如上图所示。
plot() 文档有完整的格式化字符串参数说明。axis() 命令指定坐标范围[xmin, xmax, ymin, ymax]。
例子:
01.
# -*- coding: utf-
8
-*-
02.
import
numpy as np
03.
import
matplotlib.pyplot as plt
04.
05.
# evenly sampled time at 200ms intervals
06.
t = np.arange(
0
.,
5
.,
0.2
)
07.
# red dashes, blue squares and green triangles
08.
plt.plot(t, t,
'r--'
, t, t**
2
,
'bs'
, t, t**
3
,
'g^'
)
09.
plt.show()
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 1、利用关键字:1.
plt.plot(x, y, linewidth=
2.0
)
1.
line1, line2 = plot(x1,y1,x2,y2)
2.
line.set_antialiased(False) # turn off antialising
1.
lines = plt.plot(x1, y1, x2, y2)
2.
# use key<a href=
"http://www.it165.net/edu/ebg/"
target=
"_blank"
class
=
"keylink"
>word</a> args
3.
plt.setp(lines, color=
'r'
, linewidth=
2.0
)
4.
# or MATLAB style string value pairs
5.
plt.setp(lines,
'color'
,
'r'
,
'linewidth'
,
2.0
)
4、To get a list of settable line properties, call the setp() function with a line or lines as argument 例如:
1.
lines = plt.plot([
1
,
2
,
3
])
2.
3.
plt.setp(lines)
4.
alpha:
float
5.
animated: [True | False]
6.
antialiased or aa: [True | False]
7.
...snip
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 (amatplotlib.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.MATLAB和pyplot,有当前图和当前轴的概念。所有的绘图命令适用于当前轴。gca()方法返回当前轴(一个matplotlib.axes.axes实例),和gcf()方法返回当前图形(matplotlib.figure.figure实例)。通常,你不用担心这个,因为它是幕后自动管理的。下面是一个脚本来创建两个图。
01.
# -*- coding: utf-
8
-*-
02.
import
numpy as np
03.
import
matplotlib.pyplot as plt
04.
05.
def f(t):
06.
return
np.exp(-t) * np.cos(
2
*np.pi*t)
07.
08.
t1 = np.arange(
0.0
,
5.0
,
0.1
)
09.
t2 = np.arange(
0.0
,
5.0
,
0.02
)
10.
11.
plt.figure(
1
)
12.
plt.subplot(
211
)
13.
plt.plot(t1, f(t1),
'bo'
, t2, f(t2),
'k'
)
14.
15.
plt.subplot(
212
)
16.
plt.plot(t2, np.cos(
2
*np.pi*t2),
'r--'
)
17.
plt.show()
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 an axes. Thesubplot() 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. Sosubplot(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, ie, not on a rectangular grid, use theaxes() 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_examples example code: axes_demo.py for an example of placing axes manually and pylab_examples example code: line_styles.py for an example with lots-o-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:
这里的figure()指令是可选的因为figure(1)默认会被创建,就像subplot(111)将默认创建当你不手动指定axes的情况下。该subplot()命令指定numrows,numcols,fignum范围从1到numrows * numcols【即211为2行1列第1幅图,和MATLAB相同】。如果numrows * numcols<10,subplot()命令中的逗号是可选的。您可以创建任意数量的subplots和axes。如果你想手动设置一个axes,可以使用axes()命令,它允许你指定的位置为axes([left, bottom, width, height]),所有的值都是分数(0~1)坐标。01.
# -*- coding: utf-
8
-*-
02.
import
matplotlib.pyplot as plt
03.
plt.figure(
1
) # the first figure
04.
plt.subplot(
211
) # the first subplot in the first figure
05.
plt.plot([
1
,
2
,
3
])
06.
plt.subplot(
212
) # the second subplot in the first figure
07.
plt.plot([
4
,
5
,
6
])
08.
09.
10.
plt.figure(
2
) # a second figure
11.
plt.plot([
4
,
5
,
6
]) # creates a subplot(
111
) by
default
12.
13.
plt.figure(
1
) # figure
1
current; subplot(
212
) still current
14.
plt.subplot(
211
) # make subplot(
211
) in figure1 current
15.
plt.title(
'Easy as 1,2,3'
) # subplot
211
title
16.
plt.show()
You can clear the current figure with clf() and the current axes with cla(). If you find this statefulness, annoying, 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 a long sequence 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)添加标签!怎么添加中文标签?!
01.
# -*- coding: utf-
8
-*-
02.
import
numpy as np
03.
import
matplotlib.pyplot as plt
04.
05.
mu, sigma =
100
,
15
06.
x = mu + sigma * np.random.randn(
10000
)
07.
08.
# the histogram of the data
09.
n, bins, patches = plt.hist(x,
50
, normed=
1
, facecolor=
'g'
, alpha=
0.75
)
10.
11.
12.
plt.xlabel(
'Smarts'
)
13.
plt.ylabel(u
'概率'
, fontproperties=
'SimHei'
)
14.
plt.title(u
'IQ直方图'
, fontproperties=
'SimHei'
)
15.
plt.text(
60
, .
025
, r
'$mu=100, sigma=15$'
)
16.
plt.axis([
40
,
160
,
0
,
0.03
])
17.
plt.grid(True)
18.
plt.show()
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():
1.
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. For example to write the expression in the title, you can write a TeX expression surrounded by dollar signs:
1.
plt.title(r
'$sigma_i=15$'
)
The r preceding the title string is important – it signifies that the string is a raw string and not to treat backslashes and 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.
Annotating text
The uses of the basic text() command above place text at an arbitrary position on the Axes. A common use case of 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.
01.
# -*- coding: utf-
8
-*-
02.
import
numpy as np
03.
import
matplotlib.pyplot as plt
04.
05.
ax = plt.subplot(
111
)
06.
07.
t = np.arange(
0.0
,
5.0
,
0.01
)
08.
s = np.cos(
2
*np.pi*t)
09.
line, = plt.plot(t, s, lw=
2
)
10.
11.
plt.annotate(
'local max'
, xy=(
2
,
1
), xytext=(
3
,
1.5
),
12.
arrowprops=dict(facecolor=
'black'
, shrink=
0.05
),
13.
)
14.
15.
plt.ylim(-
2
,
2
)
16.
plt.show()
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 – seeAnnotating text and Annotating Axes for details. More examples can be found in pylab_examples example code: annotation_demo.py.
其他
这部分内容具体请看:点击打开链接横向图形:
01.
from matplotlib
import
pyplot as plt
02.
from numpy
import
sin, exp, absolute, pi, arange
03.
from numpy.random
import
normal
04.
05.
06.
def f(t):
07.
s1 = sin(
2
* pi * t)
08.
e1 = exp(-t)
09.
return
absolute((s1 * e1)) + .
05
10.
11.
12.
t = arange(
0.0
,
5.0
,
0.1
)
13.
s = f(t)
14.
nse = normal(
0.0
,
0.3
, t.shape) * s
15.
16.
fig = plt.figure(figsize=(
12
,
6
))
17.
vax = fig.add_subplot(
121
)
18.
hax = fig.add_subplot(
122
)
19.
20.
vax.plot(t, s + nse,
'b^'
)
21.
vax.vlines(t, [
0
], s)
22.
vax.set_xlabel(
'time (s)'
)
23.
vax.set_title(
'Vertical lines demo'
)
24.
25.
hax.plot(s + nse, t,
'b^'
)
26.
hax.hlines(t, [
0
], s, lw=
2
)
27.
hax.set_xlabel(
'time (s)'
)
28.
hax.set_title(
'Horizontal lines demo'
)
29.
30.
plt.show()
点状分布图:
01.
import
numpy as np
02.
import
matplotlib.pyplot as plt
03.
04.
05.
N =
50
06.
x = np.random.rand(N)
07.
y = np.random.rand(N)
08.
area = np.pi * (
15
* np.random.rand(N))**
2
#
0
to
15
point radiuses
09.
10.
plt.scatter(x, y, s=area, alpha=
0.5
)
11.
plt.show()
总结
1、颜色控制:
b:blue ,c:cyan,g:green,k:black,m:magenta,r:red ,w:white, y:yellow。控制颜色方法: 简称或者全称:如上所列; 16进制:FF00FF; RGB或RGBA元组:(1,0,1,1);
灰度强度如:0.7;(大量颜色处理适用,不重复的随机数即可)
2、线型控制:
- 实线; -- 短线; -. 短点相间线; : 虚点线- matplotlib 2D绘图基础
- matplotlib绘图基础--2
- Matplotlib学习笔记1-2D绘图
- Matplotlib 绘图教程(2D入门)
- Matplotlib 绘图教程(2D进阶)
- matplotlib-3D绘图
- 2D绘图基础
- 2D绘图基础
- matplotlib绘图基础
- matplotlib绘图基础
- matplotlib绘图基础
- matplotlib绘图基础
- matplotlib绘图基础--1
- matplotlib绘图基础--3
- matplotlib绘图基础
- matplotlib绘图基础--笔记
- [053]matplotlib绘图基础
- Matplotlib 绘图教程(3D)
- 图解autoscan、aclocal、autoheader、automake、autoconf、configure、make
- error:devoce not found或error device offline解决方式
- oracle客户端备份导入导出数据库(exp,imp)
- PHP获取客户端IP地址
- EXPORT_SYMBOL与EXPORT_SYMBOL_GPL
- matplotlib 2D绘图基础
- Unity Transform(变换)和Input
- iOS8 定位新增功能
- 【 Android】handler异步消息处理机制完全解析,带你从源码的角度彻底理解
- TI的ZigBee协议栈不同版本的区别,如何选择合适的协议栈进行产品开发
- Hibernate基础学习总结
- Linux命令之mpstat
- 阐明iOS证书和provision文件
- 使用 Eclipse 的 SVN 插件创建项目的主干/分支/标签