数据可视化(Matplotlib)
1.基本绘图
plot(水平坐标, 垂直坐标)
2.线型、线宽和颜色
plot(..., linestyle=线型, linewidth=线宽, color=颜色, ...)
线型:[-]/--/:/-./o/o-/...
线宽:0-oo
color:dodgerblue/orangered/limegreen/red/blue/...
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as mp
x = np.linspace(-np.pi, np.pi, 1000)
cos_y = np.cos(x) / 2
sin_y = np.sin(x)
mp.plot(x, cos_y, linestyle='--', linewidth=1,
color='dodgerblue')
mp.plot(x, sin_y, linestyle='-.', linewidth=3,
color='orangered')
mp.show()
3.设置坐标范围
xlim(水平坐标最小值,水平坐标最大值)
ylim(垂直坐标最小值,垂直坐标最大值)
坐标范围越大,图形越小,反而反之。
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as mp
x = np.linspace(-np.pi, np.pi, 1000)
cos_y = np.cos(x) / 2
sin_y = np.sin(x)
mp.xlim(x.min() * 1.1, x.max() * 1.1)
mp.ylim(sin_y.min() * 1.1, sin_y.max() * 1.1)
mp.plot(x, cos_y, linestyle='--', linewidth=1,
color='dodgerblue')
mp.plot(x, sin_y, linestyle='-.', linewidth=3,
color='orangered')
mp.show()
4.设置坐标刻度
xticks(水平轴刻度位置[, 水平轴刻度文本])
yticks(垂直轴刻度位置[, 垂直轴刻度文本])
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as mp
x = np.linspace(-np.pi, np.pi, 1000)
cos_y = np.cos(x) / 2
sin_y = np.sin(x)
mp.xlim(x.min() * 1.1, x.max() * 1.1)
mp.ylim(sin_y.min() * 1.1, sin_y.max() * 1.1)
mp.xticks([-np.pi, -np.pi / 2, 0,
np.pi / 2, np.pi * 3 / 4, np.pi],
[r'$-\pi$', r'$-\frac{\pi}{2}$', r'$0$',
r'$\frac{\pi}{2}$', r'$\frac{3\pi}{4}$',
r'$\pi$'])
mp.yticks([-1, -0.5, 0.5, 1])
mp.plot(x, cos_y, linestyle='--', linewidth=1,
color='dodgerblue')
mp.plot(x, sin_y, linestyle='-.', linewidth=3,
color='orangered')
mp.show()
5.设置坐标轴属性
ax = gca() # 获取当前坐标轴图
ax.spines['left'] -> 左纵轴
ax.spines['right'] -> 右纵轴
ax.spines['top'] -> 上横轴
ax.spines['bottom'] -> 下横轴
XX轴.set_position((坐标系, 位置值)) # 设置位置
XX轴.set_color(颜色) # 设置颜色
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as mp
x = np.linspace(-np.pi, np.pi, 1000)
cos_y = np.cos(x) / 2
sin_y = np.sin(x)
mp.xlim(x.min() * 1.1, x.max() * 1.1)
mp.ylim(sin_y.min() * 1.1, sin_y.max() * 1.1)
mp.xticks([-np.pi, -np.pi / 2, 0,
np.pi / 2, np.pi * 3 / 4, np.pi],
[r'$-\pi$', r'$-\frac{\pi}{2}$', r'$0$',
r'$\frac{\pi}{2}$', r'$\frac{3\pi}{4}$',
r'$\pi$'])
mp.yticks([-1, -0.5, 0.5, 1])
ax = mp.gca()
ax.spines['left'].set_position(('data', 0))
ax.spines['bottom'].set_position(('data', 0))
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
mp.plot(x, cos_y, linestyle='--', linewidth=1,
color='dodgerblue')
mp.plot(x, sin_y, linestyle='-.', linewidth=3,
color='orangered')
mp.show()
6.图例
plot(..., label=图例标签, ...)
legend([loc=显示位置])
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as mp
x = np.linspace(-np.pi, np.pi, 1000)
cos_y = np.cos(x) / 2
sin_y = np.sin(x)
mp.xlim(x.min() * 1.1, x.max() * 1.1)
mp.ylim(sin_y.min() * 1.1, sin_y.max() * 1.1)
mp.xticks([-np.pi, -np.pi / 2, 0,
np.pi / 2, np.pi * 3 / 4, np.pi],
[r'$-\pi$', r'$-\frac{\pi}{2}$', r'$0$',
r'$\frac{\pi}{2}$', r'$\frac{3\pi}{4}$',
r'$\pi$'])
mp.yticks([-1, -0.5, 0.5, 1])
ax = mp.gca()
ax.spines['left'].set_position(('data', 0))
ax.spines['bottom'].set_position(('data', 0))
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
mp.plot(x, cos_y, linestyle='--', linewidth=1,
color='dodgerblue',
label=r'$y=\frac{1}{2}cos(x)$')
mp.plot(x, sin_y, linestyle='-.', linewidth=3,
color='orangered',
label=r'$y=sin(x)$')
mp.legend()
mp.show()
7.添加特殊点
scatter(水平坐标, 垂直坐标, s=大小, marker=点形,
edgecolor=边缘色, facecolor=填充色,
zorder=Z顺序)
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as mp
x = np.linspace(-np.pi, np.pi, 1000)
cos_y = np.cos(x) / 2
sin_y = np.sin(x)
xo = np.pi * 3 / 4
yo_cos = np.cos(xo) / 2
yo_sin = np.sin(xo)
mp.xlim(x.min() * 1.1, x.max() * 1.1)
mp.ylim(sin_y.min() * 1.1, sin_y.max() * 1.1)
mp.xticks([-np.pi, -np.pi / 2, 0,
np.pi / 2, np.pi * 3 / 4, np.pi],
[r'$-\pi$', r'$-\frac{\pi}{2}$', r'$0$',
r'$\frac{\pi}{2}$', r'$\frac{3\pi}{4}$',
r'$\pi$'])
mp.yticks([-1, -0.5, 0.5, 1])
ax = mp.gca()
ax.spines['left'].set_position(('data', 0))
ax.spines['bottom'].set_position(('data', 0))
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
mp.plot(x, cos_y, linestyle='--', linewidth=1,
color='dodgerblue',
label=r'$y=\frac{1}{2}cos(x)$')
mp.plot(x, sin_y, linestyle='-.', linewidth=3,
color='orangered',
label=r'$y=sin(x)$')
mp.plot([xo, xo], [yo_cos, yo_sin], linewidth=0.5,
color='limegreen')
mp.scatter([xo, xo], [yo_cos, yo_sin], s=60,
edgecolor='limegreen', facecolor='white',
marker='D', zorder=3)
mp.annotate(
r'$\frac{1}{2}cos(\frac{3\pi}{4})=-\frac{\sqrt{2}}{4}$',
xy=(xo, yo_cos), xycoords='data',
xytext=(-90, -40), textcoords='offset points',
fontsize=14,
arrowprops=dict(arrowstyle='->',
connectionstyle='arc3, rad=.2'))
mp.annotate(
r'$sin(\frac{3\pi}{4})=\frac{\sqrt{2}}{2}$',
xy=(xo, yo_sin), xycoords='data',
xytext=(20, 20), textcoords='offset points',
fontsize=14,
arrowprops=dict(arrowstyle='->',
connectionstyle='arc3, rad=.2'))
mp.legend(loc='upper left')
mp.show()
8.备注
annotate(
备注文本,
xy=目标坐标,
xycoords=目标坐标系,
xytext=文本坐标,
textcoords=文本坐标系,
fontsize=字体大小,
arrowprops=箭头属性)
9.图形(窗口)对象
figure(窗口名(标题栏文本), figsize=大小, dpi=分辨率,
facecolor=颜色)
如果与指定窗口名对应的图形对象不存在,那么就新建一个图形窗口,如果已存在,那么不会再新建图形窗口,而是将已存在的那个图形窗口设置为当前窗口。
title(窗口标题, fontsize=字体大小)
xlabel(水平轴标签, fontsize=字体大小)
ylabel(垂直轴标签, fontsize=字体大小)
tick_params(labelsize=刻度标签字体大小)
grid(linestyle=网格线型)
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as mp
x = np.linspace(-np.pi, np.pi, 1000)
cos_y = np.cos(x) / 2
sin_y = np.sin(x)
mp.figure('Figure Object 1', figsize=(6, 4),
dpi=120, facecolor='lightgray')
mp.title('Figure Object 1', fontsize=20)
mp.xlabel('x', fontsize=14)
mp.ylabel('y', fontsize=14)
mp.tick_params(labelsize=10)
mp.grid(linestyle=':')
mp.figure('Figure Object 2', figsize=(6, 4),
dpi=120, facecolor='lightgray')
mp.title('Figure Object 2', fontsize=20)
mp.xlabel('x', fontsize=14)
mp.ylabel('y', fontsize=14)
mp.tick_params(labelsize=10)
mp.grid(linestyle=':')
mp.figure('Figure Object 1')
mp.plot(x, cos_y, color='dodgerblue',
label=r'$y=\frac{1}{2}cos(x)$')
mp.legend()
mp.figure('Figure Object 2')
mp.plot(x, sin_y, color='orangered',
label=r'$y=sin(x)$')
mp.legend()
mp.show()
10.子坐标图
1)矩阵布局
1 2
3 4
subplot(行数, 列数, 图号) # 创建子图
tight_layout() # 紧凑布局
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import matplotlib.pyplot as mp
mp.figure('Matrix Layout', facecolor='lightgray')
mp.subplot(221)
mp.xticks(())
mp.yticks(())
mp.text(0.5, 0.5, '1', ha='center', va='center',
size=36, alpha=0.5)
mp.subplot(222)
mp.xticks(())
mp.yticks(())
mp.text(0.5, 0.5, '2', ha='center', va='center',
size=36, alpha=0.5)
mp.subplot(223)
mp.xticks(())
mp.yticks(())
mp.text(0.5, 0.5, '3', ha='center', va='center',
size=36, alpha=0.5)
mp.subplot(224)
mp.xticks(())
mp.yticks(())
mp.text(0.5, 0.5, '4', ha='center', va='center',
size=36, alpha=0.5)
mp.tight_layout()
mp.show()
2)栅格布局
import matplotlib.gridspec as mg
栅格定位器 = mg.GridSpec(行数, 列数)
subplot(栅格定位器[行, 列])
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import matplotlib.pyplot as mp
import matplotlib.gridspec as mg
mp.figure('Grid Layout', facecolor='lightgray')
gs = mg.GridSpec(3, 3)
mp.subplot(gs[0, :2])
mp.xticks(())
mp.yticks(())
mp.text(0.5, 0.5, '1', ha='center', va='center',
size=36, alpha=0.5)
mp.subplot(gs[1:, 0])
mp.xticks(())
mp.yticks(())
mp.text(0.5, 0.5, '2', ha='center', va='center',
size=36, alpha=0.5)
mp.subplot(gs[2, 1:])
mp.xticks(())
mp.yticks(())
mp.text(0.5, 0.5, '3', ha='center', va='center',
size=36, alpha=0.5)
mp.subplot(gs[:2, 2])
mp.xticks(())
mp.yticks(())
mp.text(0.5, 0.5, '4', ha='center', va='center',
size=36, alpha=0.5)
mp.subplot(gs[1, 1])
mp.xticks(())
mp.yticks(())
mp.text(0.5, 0.5, '5', ha='center', va='center',
size=36, alpha=0.5)
mp.tight_layout()
mp.show()
3)自由布局
axes([左, 底, 宽, 高]) # 归一化单位
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import matplotlib.pyplot as mp
mp.figure('Free Layout', facecolor='lightgray')
mp.axes([0.03, 0.038, 0.94, 0.924])
mp.xticks(())
mp.yticks(())
mp.text(0.5, 0.5, '1', ha='center', va='center',
size=36, alpha=0.5)
mp.axes([0.63, 0.076, 0.31, 0.308])
mp.xticks(())
mp.yticks(())
mp.text(0.5, 0.5, '2', ha='center', va='center',
size=36, alpha=0.5)
mp.show()
11.刻度定位器
刻度定位器 = xxxLocator(定位规则)
ax = gca()
ax.xaxis -> 水平坐标轴
ax.yaxis -> 垂直坐标轴
坐标轴.set_major_locator(刻度定位器) # 主刻度
坐标轴.set_minor_locator(刻度定位器) # 次刻度
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as mp
mp.figure()
locators = [
'mp.NullLocator()',
'mp.MaxNLocator(nbins=3, steps=[1, 3, 5, 7, 9])',
'mp.FixedLocator(locs=[0, 2.5, 5, 7.5, 10])',
'mp.AutoLocator()',
'mp.IndexLocator(offset=0.5, base=1.5)',
'mp.MultipleLocator()',
'mp.LinearLocator(numticks=21)',
'mp.LogLocator(base=2, subs=[1.0])']
n_locators = len(locators)
for i, locator in enumerate(locators):
mp.subplot(n_locators, 1, i + 1)
mp.xlim(0, 10)
mp.ylim(-1, 1)
mp.yticks(())
ax = mp.gca()
ax.spines['left'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_position(('data', 0))
ax.xaxis.set_major_locator(eval(locator))
ax.xaxis.set_minor_locator(mp.MultipleLocator(0.1))
mp.plot(np.arange(11), np.zeros(11), c='none')
mp.text(5, 0.3, locator[3:], ha='center', size=12)
mp.tight_layout()
mp.show()
想要看更多的课程请微信关注SkrEric的编程课堂