我是靠谱客的博主 明亮刺猬,最近开发中收集的这篇文章主要介绍数据分析--数据可视化(Matplotlib),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

数据可视化(Matplotlib)
1.基本绘图

plot(水平坐标, 垂直坐标)
numpy.linspace(start,stop,num = 50,endpoint = True,retstep = False,
dtype = None )
在指定的间隔内返回均匀间隔的数字。返回num均匀间隔的样本,在[ start,stop ] 区间内计算。
可以选择排除间隔的终点。
参数:
start(开始): 标量
序列的起始值。
end(停止) : 标量序列的结束值,除非端点设置为False。在这种情况下,序列由除均匀间隔的
样本之外的所有样本组成,因此不包括停止。请注意,当端点为False 时,步长会发生变化。num
+ 1
num : int,可选,
要生成的样本数。默认值为50.必须为非负数。
endpoint(端点) : bool,可选如果为True,则stop是最后一个样本。否则,它不包括在内。
默认为True。
retstep : bool,可选如果为True,则返回(samples,step),其中step是样本之间的
间距。
dtype : dtype,可选
输出数组的类型。如果dtype未给出,则从其他输入参数推断数据类型。
返回:
样品 : ndarray
有NUM同样在闭区间隔开的样品 或半开间隔 (取决于是否端点是真或假)。[start, stop]
[start, stop)
步骤:浮动,可选
仅在retstep为True 时才返回
样本之间的间距大小。

代码:

	# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as mp
x = np.linspace(-np.pi, np.pi, 1000) # 范围从-π到π,生成1000个点
cos_y = np.cos(x)
sin_y = np.sin(x)
mp.plot(x, cos_y)
mp.plot(x, sin_y)
mp.show()
# 必须有np.show()否则生成的图像保存在内存中,展示不出来

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{3pi}{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{3pi}{4}$',
r'$pi$'])
mp.yticks([-1, -0.5, 0.5, 1])
# 设置横纵坐标(0,0),将图像放在坐标的中间
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{3pi}{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)
# 自定义点的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{3pi}{4}$',
r'$pi$'])
mp.yticks([-1, -0.5, 0.5, 1])
# 设置(0,0)点为坐标原点
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{3pi}{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{3pi}{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()

12.区域填充

fill_between(
水平坐标, 起点垂直坐标, 终点垂直坐标, 填充条件,
color=颜色, alpha=透明度)

代码:

	# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as mp
# 生成数据
n = 1000
x = np.linspace(0, 8 * np.pi, n)
sin_y = np.sin(x)
cos_y = np.cos(x / 2) / 2
# 创建图形窗口
mp.figure('Fill', facecolor='lightgray')
# 设置窗口标题
mp.title('Fill', fontsize=20)
# 设置坐标轴标签
mp.xlabel('x', fontsize=14)
mp.ylabel('y', fontsize=14)
# 设置刻度参数
mp.tick_params(labelsize=10)
# 设置网格线型
mp.grid(linestyle=':')
# 绘制曲线
mp.plot(x, sin_y, c='dodgerblue',
label=r'$y=sin(x)$')
mp.plot(x, cos_y, c='orangered',
label=r'$y=frac{1}{2}cos(frac{x}{2})$')
# 绘制填充区域
mp.fill_between(x, cos_y, sin_y, cos_y < sin_y,
color='dodgerblue', alpha=0.5)
mp.fill_between(x, cos_y, sin_y, cos_y > sin_y,
color='orangered', alpha=0.5)
# 绘制图例
mp.legend()
# 显示图形
mp.show()

最后

以上就是明亮刺猬为你收集整理的数据分析--数据可视化(Matplotlib)的全部内容,希望文章能够帮你解决数据分析--数据可视化(Matplotlib)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(44)

评论列表共有 0 条评论

立即
投稿
返回
顶部