matplotlib-1
李金的中文Python笔记[https://github.com/lijin-thu/notes-python]的学习笔记及摘要。
import numpy as np
import matplotlib.pyplot as plt
Pyplot 教程
plt.plot() 函数
和 MATLAB
中类似,我们还可以用字符来指定绘图的格式:
表示颜色的字符参数有:
字符 | 颜色 |
---|---|
‘b’ | 蓝色,blue |
‘g’ | 绿色,green |
‘r’ | 红色,red |
‘c’ | 青色,cyan |
‘m’ | 品红,magenta |
‘y’ | 黄色,yellow |
‘k’ | 黑色,black |
‘w’ | 白色,white |
表示类型的字符参数有:
字符 | 类型 | 字符 | 类型 |
---|---|---|---|
'-' | 实线 | '--' | 虚线 |
'-.' | 虚点线 | ':' | 点线 |
'.' | 点 | ',' | 像素点 |
'o' | 圆点 | 'v' | 下三角点 |
'^' | 上三角点 | '<' | 左三角点 |
'>' | 右三角点 | '1' | 下三叉点 |
'2' | 上三叉点 | '3' | 左三叉点 |
'4' | 右三叉点 | 's' | 正方点 |
'p' | 五角点 | '*' | 星形点 |
'h' | 六边形点1 | 'H' | 六边形点2 |
'+' | 加号点 | 'x' | 乘号点 |
'D' | 实心菱形点 | 'd' | 瘦菱形点 |
'_' | 横线点 |
图形上加上文字
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
# the histogram of the data
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()
使用 style 来配置 pyplot 风格
x = np.linspace(0, 2 * np.pi)
y = np.sin(x)
plt.plot(x, y)
plt.show()
plt.style.use('ggplot') # 模仿 R 语言中常用的 ggplot 风格
plt.plot(x, y)
plt.show()
处理文本
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
基本文本函数
在 matplotlib.pyplot
中,基础的文本函数如下:
text()
在Axes
对象的任意位置添加文本xlabel()
添加 x 轴标题ylabel()
添加 y 轴标题title()
给Axes
对象添加标题figtext()
在Figure
对象的任意位置添加文本suptitle()
给Figure
对象添加标题anotate()
给Axes
对象添加注释(可选择是否添加箭头标记)
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
%matplotlib inline
# plt.figure() 返回一个 Figure() 对象
fig = plt.figure(figsize=(12, 9))
# 设置这个 Figure 对象的标题
# 事实上,如果我们直接调用 plt.suptitle() 函数,它会自动找到当前的 Figure 对象
fig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold')
# Axes 对象表示 Figure 对象中的子图
# 这里只有一幅图像,所以使用 add_subplot(111)
ax = fig.add_subplot(111)
fig.subplots_adjust(top=0.85)
# 可以直接使用 set_xxx 的方法来设置标题
ax.set_title('axes title')
# 也可以直接调用 title(),因为会自动定位到当前的 Axes 对象
# plt.title('axes title')
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')
# 添加文本,斜体加文本框
ax.text(3, 8, 'boxed italics text in data coords', style='italic',
bbox={'facecolor':'red', 'alpha':0.5, 'pad':10})
# 数学公式,用 $$ 输入 Tex 公式
ax.text(2, 6, r'an equation: $E=mc^2$', fontsize=15)
# Unicode 支持
#ax.text(3, 2, unicode('unicode: Institut f\374r Festk\366rperphysik', 'latin-1'))
# 颜色,对齐方式
ax.text(0.95, 0.01, 'colored text in axes coords',
verticalalignment='bottom', horizontalalignment='right',
transform=ax.transAxes,
color='green', fontsize=15)
# 注释文本和箭头
ax.plot([2], [1], 'o')
ax.annotate('annotate', xy=(2, 1), xytext=(3, 4),
arrowprops=dict(facecolor='black', shrink=0.05))
# 设置显示范围
ax.axis([0, 10, 0, 10])
plt.show()
文本属性和布局
我们可以通过下列关键词,在文本函数中设置文本的属性:
关键词 | 值 |
---|---|
alpha | float |
backgroundcolor | any matplotlib color |
bbox | rectangle prop dict plus key 'pad' which is a pad in points |
clip_box | a matplotlib.transform.Bbox instance |
clip_on | [True , False] |
clip_path | a Path instance and a Transform instance, a Patch |
color | any matplotlib color |
family | [ 'serif' , 'sans-serif' , 'cursive' , 'fantasy' , 'monospace' ] |
fontproperties | a matplotlib.font_manager.FontProperties instance |
horizontalalignment or ha | [ 'center' , 'right' , 'left' ] |
label | any string |
linespacing | float |
multialignment | ['left' , 'right' , 'center' ] |
name or fontname | string e.g., ['Sans' , 'Courier' , 'Helvetica' …] |
picker | [None,float,boolean,callable] |
position | (x,y) |
rotation | [ angle in degrees 'vertical' , 'horizontal' |
size or fontsize | [ size in points , relative size, e.g., 'smaller' , 'x-large' ] |
style or fontstyle | [ 'normal' , 'italic' , 'oblique' ] |
text | string or anything printable with ‘%s’ conversion |
transform | a matplotlib.transform transformation instance |
variant | [ 'normal' , 'small-caps' ] |
verticalalignment or va | [ 'center' , 'top' , 'bottom' , 'baseline' ] |
visible | [True , False] |
weight or fontweight | [ 'normal' , 'bold' , 'heavy' , 'light' , 'ultrabold' , 'ultralight' ] |
x | float |
y | float |
zorder | any number |
其中 va
, ha
, multialignment
可以用来控制布局。
horizontalalignment
orha
:x 位置参数表示的位置verticalalignment
orva
:y 位置参数表示的位置multialignment
:多行位置控制
import matplotlib.pyplot as plt
import matplotlib.patches as patches
# build a rectangle in axes coords
left, width = .25, .5
bottom, height = .25, .5
right = left + width
top = bottom + height
fig = plt.figure(figsize=(10,7))
ax = fig.add_axes([0,0,1,1])
# axes coordinates are 0,0 is bottom left and 1,1 is upper right
p = patches.Rectangle(
(left, bottom), width, height,
fill=False, transform=ax.transAxes, clip_on=False
)
ax.add_patch(p)
ax.text(left, bottom, 'left top',
horizontalalignment='left',
verticalalignment='top',
transform=ax.transAxes,
size='xx-large')
ax.text(left, bottom, 'left bottom',
horizontalalignment='left',
verticalalignment='bottom',
transform=ax.transAxes,
size='xx-large')
ax.text(right, top, 'right bottom',
horizontalalignment='right',
verticalalignment='bottom',
transform=ax.transAxes,
size='xx-large')
ax.text(right, top, 'right top',
horizontalalignment='right',
verticalalignment='top',
transform=ax.transAxes,
size='xx-large')
ax.text(right, bottom, 'center top',
horizontalalignment='center',
verticalalignment='top',
transform=ax.transAxes,
size='xx-large')
ax.text(left, 0.5*(bottom+top), 'right center',
horizontalalignment='right',
verticalalignment='center',
rotation='vertical',
transform=ax.transAxes,
size='xx-large')
ax.text(left, 0.5*(bottom+top), 'left center',
horizontalalignment='left',
verticalalignment='center',
rotation='vertical',
transform=ax.transAxes,
size='xx-large')
ax.text(0.5*(left+right), 0.5*(bottom+top), 'middle',
horizontalalignment='center',
verticalalignment='center',
fontsize=20, color='red',
transform=ax.transAxes)
ax.text(right, 0.5*(bottom+top), 'centered',
horizontalalignment='center',
verticalalignment='center',
rotation='vertical',
transform=ax.transAxes,
size='xx-large')
ax.text(left, top, 'rotated\nwith newlines',
horizontalalignment='center',
verticalalignment='center',
rotation=45,
transform=ax.transAxes,
size='xx-large')
ax.set_axis_off()
plt.show()
数学表达式
在字符串中使用一对 $$
符号可以利用 Tex
语法打出数学表达式,而且并不需要预先安装 Tex
。在使用时我们通常加上 r
标记表示它是一个原始字符串(raw string)
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
# plain text
plt.title('alpha > beta')
plt.show()
# math text
plt.title(r'$\alpha > \beta$')
plt.show()
根号
2
\sqrt{2}
2: r'$\sqrt{2}$
x
3
\sqrt[3]{x}
3x:r'$\sqrt[3]{x}$
特殊字体
默认显示的字体是斜体,不过可以使用以下方法显示不同的字体:
命令 | 显示 |
---|---|
\mathrm{Roman} | R o m a n \mathrm{Roman} Roman |
\mathit{Italic} | I t a l i c \mathit{Italic} Italic |
\mathtt{Typewriter} | T y p e w r i t e r \mathtt{Typewriter} Typewriter |
\mathcal{CALLIGRAPHY} | C A L L I G R A P H Y \mathcal{CALLIGRAPHY} CALLIGRAPHY |
\mathbb{blackboard} | b l a c k b o a r d \mathbb{blackboard} blackboard |
\mathfrak{Fraktur} | F r a k t u r \mathfrak{Fraktur} Fraktur |
\mathsf{sansserif} | s a n s s e r i f \mathsf{sansserif} sansserif |
s
(
t
)
=
A
sin
(
2
ω
t
)
s(t) = \mathcal{A}\ \sin(2 \omega t)
s(t)=A sin(2ωt):s(t) = \mathcal{A}\ \sin(2 \omega t)
注:
- Tex 语法默认忽略空格,要打出空格使用
'\ '
- \sin 默认显示为 Roman 字体
音调
命令 | 结果 |
---|---|
\acute a | a ˊ \acute a aˊ |
\bar a | a ˉ \bar a aˉ |
\breve a | a ˘ \breve a a˘ |
\ddot a | a ¨ \ddot a a¨ |
\dot a | a ˙ \dot a a˙ |
\grave a | a ˋ \grave a aˋ |
\hat a | a ^ \hat a a^ |
\tilde a | a ~ \tilde a a~ |
\4vec a | a ⃗ \vec a a |
\overline{abc} | a b c ‾ \overline{abc} abc |
\widehat{xyz} | x y z ^ \widehat{xyz} xyz |
\widetilde{xyz} | x y z ~ \widetilde{xyz} xyz |
特殊字符表
参见:http://matplotlib.org/users/mathtext.html#symbols
标签 06.07-legend
待深入学习
figures, subplots, axes 和 ticks 对象
figures, axes 和 ticks 的关系
这些对象的关系可以用下面的图来表示:
示例图像:
具体结构:
figure 对象
figure
对象是最外层的绘图单位,默认是以 1
开始编号(MATLAB 风格,Figure 1, Figure 2, ...
),可以用 plt.figure()
产生一幅图像,除了默认参数外,可以指定的参数有:
num
- 编号figsize
- 图像大小dpi
- 分辨率facecolor
- 背景色edgecolor
- 边界颜色frameon
- 边框
这些属性也可以通过 Figure
对象的 set_xxx
方法来改变。
subplot
%pylab inline
subplot(2,1,1)
xticks([]), yticks([])
text(0.5,0.5, 'subplot(2,1,1)',ha='center',va='center',size=24,alpha=.5)
subplot(2,1,2)
xticks([]), yticks([])
text(0.5,0.5, 'subplot(2,1,2)',ha='center',va='center',size=24,alpha=0.5)
show()
- 更高级的可以用
gridspec
来绘图:
import matplotlib.gridspec as gridspec
G = gridspec.GridSpec(3, 3)
axes_1 = subplot(G[0, :])
xticks([]), yticks([])
text(0.5,0.5, 'Axes 1',ha='center',va='center',size=24,alpha=.5)
axes_2 = subplot(G[1,:-1])
xticks([]), yticks([])
text(0.5,0.5, 'Axes 2',ha='center',va='center',size=24,alpha=.5)
axes_3 = subplot(G[1:, -1])
xticks([]), yticks([])
text(0.5,0.5, 'Axes 3',ha='center',va='center',size=24,alpha=.5)
axes_4 = subplot(G[-1,0])
xticks([]), yticks([])
text(0.5,0.5, 'Axes 4',ha='center',va='center',size=24,alpha=.5)
axes_5 = subplot(G[-1,-2])
xticks([]), yticks([])
text(0.5,0.5, 'Axes 5',ha='center',va='center',size=24,alpha=.5)
show()
axes 对象
subplot
返回的是Axes
对象,但是Axes
对象相对于subplot
返回的对象来说要更自由一点。Axes
对象可以放置在图像中的任意位置,且后面的Axes
对象会覆盖前面的内容。
axes([0.1,0.1,.5,.5])
xticks([]), yticks([])
text(0.1,0.1, 'axes([0.1,0.1,.8,.8])',ha='left',va='center',size=16,alpha=.5)
axes([0.2,0.2,.5,.5])
xticks([]), yticks([])
text(0.1,0.1, 'axes([0.2,0.2,.5,.5])',ha='left',va='center',size=16,alpha=.5)
axes([0.3,0.3,.5,.5])
xticks([]), yticks([])
text(0.1,0.1, 'axes([0.3,0.3,.5,.5])',ha='left',va='center',size=16,alpha=.5)
axes([0.4,0.4,.5,.5])
xticks([]), yticks([])
text(0.1,0.1, 'axes([0.4,0.4,.5,.5])',ha='left',va='center',size=16,alpha=.5)
show()
ticks 对象
ticks 用来注释轴的内容,我们可以通过控制它的属性来决定在哪里显示轴、轴的内容是什么等等。