「数据科学」使用 matplotlib 进行数据可视化

matplotlib 简介

matplotlib 是 Python 最著名的绘图库,它提供了一整套和 matlab 相似的命令 API,十分适合交互式地进行制图。而且也可以方便地将它作为绘图控件,嵌入 GUI 应用程序中。

seaborn 是在 matplotlib 的基础上进行了更高级的 API 封装,是一个补充,用于绘制有吸引力和信息的统计图形。

pyecharts 是一个用于生成 Echarts 图表的类库。

plotly 是一个交互式的,开放源代码的绘图库,支持40多种独特的图表类型,涵盖各种统计,财务,地理,科学和3维用例。

mpld3 项目将 Matplotlib 和 D3.js 结合在一起。其结果是一个简单的 API,用于将 matplotlib 图形导出到 HTML 代码中。

Bokeh (Bokeh.js) 是一个 Python 交互式可视化库,支持现代化 Web 浏览器,提供非常完美的展示功能。Bokeh 的目标是使用 D3.js 样式提供优雅,简洁新颖的图形化风格,同时提供大型数据集的高性能交互功能。Boken 可以快速的创建交互式的绘图,仪表盘和数据应用。

figure 画布

可以理解为画布,如果不创建 figure 对象,matplotlib 将自动创建一个 figure 对象。

import matplotlib.pyplot as plt
import numpy as np

# 创建画布
fig = plt.figure()

# 快速绘图
arr = np.random.randn(100)
plt.plot(arr)
plt.show()

在这里插入图片描述

subplot 分割画布

可以通过 add_subplot 来分割figure,表示可以在figure的不同位置上作图。

fig.add_subplot(a, b, c)

a, b 表示将 fig 分割成 a*b 的区域

c 表示当前选中要操作的区域

注意:从1开始编号(不是从0开始)

plot绘图的区域是最后一次指定 subplot 的位置。

import matplotlib.pyplot as plt
import numpy as np

# 创建画布
fig = plt.figure()

# 分割画布
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)
ax4 = fig.add_subplot(2, 2, 4)

# 绘图
arr = np.random.randn(100)
ax2.plot(arr)
ax3.plot(arr)
ax4.plot(arr)

plt.show()

在这里插入图片描述

subplots 分割画布

同时返回新创建的 figure 和 subplot 对象列表。

fig, subplot_arr = plt.subplots(a, b)

a, b 表示将 fig 分割成 a*b 的区域

import matplotlib.pyplot as plt
import numpy as np

# 创建画布并分割画布
fig, subplot_arr = plt.subplots(2, 2)

# 绘图
subplot_arr[0, 1].hist(np.random.randn(100), bins=20, color='g', alpha=0.5)
subplot_arr[1, 1].imshow(np.random.rand(5, 5))

plt.show()

在这里插入图片描述

绘制图形

scatter 散点图

参数1: x轴坐标

参数2: y轴坐标

x = [1, 2, 3, 4]
y = [2, 4, 6, 8]
plt.scatter(x, y)
plt.show()

在这里插入图片描述

bar 柱形图

参数1: x轴坐标

参数2: 柱形高度

参数3: 柱形宽度

x = np.arange(5)
y1, y2 = np.random.randint(1, 25, size=(2, 5))
width = 0.33
ax = plt.subplot(1, 1, 1)
ax.bar(x, y1, width, color='r')
ax.bar(x+width, y2, width, color='#0000ff')
plt.show()

在这里插入图片描述

barh 水平柱形图

参数1: y轴坐标

参数2: 柱形长度

参数3: 柱形高度

x_data = ['2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018']
y_data1 = [11000, 12300, 14200, 16500, 17900, 19000, 20000, 21200]
y_data2 = [10500, 11900, 13300, 14900, 16700, 17800, 19400, 22000]
bar_height = 0.3
y = np.arange(len(x_data))
plt.barh(y, y_data1, bar_height, label='C', color='steelblue', alpha=0.8)
plt.barh(y+bar_height, y_data2, bar_height, label='Python', color='indianred', alpha=0.8)

# 设置图形标题
plt.title('C vs Python')

# 设置坐标轴名称
plt.xlabel('users')
plt.ylabel('year')

# 显示图例
plt.legend()

# 在柱形图上显示具体数据
# plt.text() 显示文本
# 参数1,参数2:设置文本显示的位置
# 参数3:设置显示的内容
# 参数ha:控制水平对齐方式
# 参数va:控制垂直对齐方式
for y, x in enumerate(y_data1):
    plt.text(x+2000, y-bar_height/2, f"{x}", ha='center', va='bottom')
for y, x in enumerate(y_data2):
    plt.text(x+2000, y+bar_height/2, f"{x}", ha='center', va='bottom')
    
plt.show()

在这里插入图片描述

pie 饼状图

参数1: 数据

explode: 将某部分爆炸出来

labels: 标签(列表)

sizes = [60, 90, 220, 180]
labels = ['Spring', 'Summer', 'Autumn', 'Winter']
colors = ['r', 'g', 'b', 'y']
explode = [0.15, 0, 0, 0]
plt.pie(sizes, explode=explode, labels=labels, colors=colors, labeldistance=1.1, autopct='%3.1f%%', shadow=True, startangle=90, pctdistance=0.6)

plt.show()

在这里插入图片描述

颜色、标记、线型

颜色

字符颜色
'b'蓝色
'g'绿色
'r'红色
'c'青色
'm'品红色
'y'黄色
'k'黑色
'w'白色

标记

字符标记
'.'
','像素 pixel
'o'圆圈 circle
'v'倒三角
'^'正三角
'<'左三角
'>'右三角

线型

字符线型
'-' or 'solid'实线
'--' or 'dashed'短横线
'-.' or 'dashdot'点划线
':' or 'dotted'虚线
'None'nothing
' 'nothing
''nothing

示例

fig, axes = plt.subplots(2)
axes[0].plot(np.random.randint(0, 100, 50), color='r', linestyle='--', marker='o', alpha=0.3)
axes[0].plot(np.random.randint(0, 100, 50), color='#33aa88', linestyle=':', marker='.')
axes[0].plot(np.random.randint(0, 100, 50), color=(0.5, 0.6, 0.3), linestyle='-', marker='v')

axes[1].plot(np.random.randint(0, 100, 50), 'ro-')
plt.show()

在这里插入图片描述

刻度、标签、图例

刻度

设置刻度范围

plt.xlim([xmin, xmax])

plt.ylim([ymin, ymax])

ax.set_xlim()

ax.set_ylim()

设置显示的刻度

plt.xticks(list)

plt.yticks(list)

ax.set_xticks(list)

ax.set_yticks(list)

标签

设置标题

ax.set_title()

设置坐标轴标签

ax.set_xlabel(list)

ax.set_ylabel(list)

设置刻度标签

ax.set_xticklabels()

ax.set_yticklabels()

图例

ax.plot(label=‘legend’)

ax.legend()

plt.legend()

loc = ‘best’ 自动选择放置图例最佳位置

示例

fig, ax = plt.subplots(1)
ax.plot(np.random.randn(1000).cumsum(), label='line0')
ax.plot(np.random.randn(1000).cumsum(), label='line1')
ax.plot(np.random.randn(1000).cumsum(), label='line2')

# 设置标题
ax.set_title('This is a title')
# 设置坐标轴标签
ax.set_xlabel('Number')
ax.set_ylabel('Month')
# 设置刻度范围
ax.set_xlim([0, 800])
ax.set_ylim([-45, 45])
# 设置刻度位置
ax.set_xticks(range(0, 800, 100))
ax.set_yticks(range(0, 45, 15))
# 设置刻度标签
ax.set_yticklabels(['Jan', 'Feb', 'Mar'])
# 显示图例
ax.legend(loc='best')

plt.show()

在这里插入图片描述

彩蛋 - Magic函数

%matplotlib inline

这是 IPython 中定义的魔法函数(Magic Function),其意义是将那些用于 matplotlib 绘制的图显示在页面里而不是弹出一个窗口,因此就不需要 plt.show() 这一语句来显示图片。

IPython 提供了功能强大、内建的 Magic函数,定义为: IPython中将任何第一个字母为 % 的行视为 Magic函数 的特殊调用,可以控制 IPython,为其增加许多系统功能。

后续文章中我们会具体学习 Magic函数,敬请关注~

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秀球Gang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值