matplotlib-1
- Pyplot 教程
- plt.plot() 函数
- 图形上加上文字
- 使用 style 来配置 pyplot 风格
- 处理文本
- 基本文本函数
- 文本属性和布局
- 数学表达式
- 根号
- 特殊字体
- 音调
- 特殊字符表
- 标签 06.07-legend
- 待深入学习
- figures, subplots, axes 和 ticks 对象
- figures, axes 和 ticks 的关系
- figure 对象
- subplot
- axes 对象
- ticks 对象
李金的中文Python笔记[https://github.com/lijin-thu/notes-python]的学习笔记及摘要。
import numpy as np
import matplotlib.pyplot as plt
Pyplot 教程
plt.plot() 函数
和 MATLAB
表示颜色的字符参数有:
字符 | 颜色 |
| 蓝色,blue |
| 绿色,green |
| 红色,red |
| 青色,cyan |
| 品红,magenta |
| 黄色,yellow |
| 黑色,black |
| 白色,white |
表示类型的字符参数有:
字符 | 类型 | 字符 | 类型 |
| 实线 |
| 虚线 |
| 虚点线 |
| 点线 |
| 点 |
| 像素点 |
| 圆点 |
| 下三角点 |
| 上三角点 |
| 左三角点 |
| 右三角点 |
| 下三叉点 |
| 上三叉点 |
| 左三叉点 |
| 右三叉点 |
| 正方点 |
| 五角点 |
| 星形点 |
| 六边形点1 |
| 六边形点2 |
| 加号点 |
| 乘号点 |
| 实心菱形点 |
| 瘦菱形点 |
| 横线点 |
图形上加上文字
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 |
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 | [ |
fontproperties | a matplotlib.font_manager.FontProperties instance |
horizontalalignment or ha | [ |
label | any string |
linespacing | float |
multialignment | [ |
name or fontname | string e.g., [ |
picker | [None,float,boolean,callable] |
position | (x,y) |
rotation | [ angle in degrees |
size or fontsize | [ size in points , relative size, e.g., |
style or fontstyle | [ |
text | string or anything printable with ‘%s’ conversion |
transform | a matplotlib.transform transformation instance |
variant | [ |
verticalalignment or va | [ |
visible | [True , False] |
weight or fontweight | [ |
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()
根号
: r'$\sqrt{2}$
:r'$\sqrt[3]{x}$
特殊字体
默认显示的字体是斜体,不过可以使用以下方法显示不同的字体:
命令 | 显示 |
\mathrm{Roman} | |
\mathit{Italic} | |
\mathtt{Typewriter} | |
\mathcal{CALLIGRAPHY} | |
\mathbb{blackboard} | |
\mathfrak{Fraktur} | |
\mathsf{sansserif} |
:s(t) = \mathcal{A}\ \sin(2 \omega t)
注:
- Tex 语法默认忽略空格,要打出空格使用
'\ '
- \sin 默认显示为 Roman 字体
音调
命令 | 结果 |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
特殊字符表
参见: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 用来注释轴的内容,我们可以通过控制它的属性来决定在哪里显示轴、轴的内容是什么等等。