Python可视化库(绘制图表):matplotlib

动机

作为一个初级JAVA工作者,最近尝试学习机器学习,看完晕头转向的一些概念之后,尝试实现了第一个PLA感知机算法,成功之后甚至想叉腰得瑟一会。正在得意洋洋之时,如何让算法结果可视化呢,网上搜索了半天发现了一个好用的python第三方库matplotlib。

matplotlib可以做什么

Matplotlib 能够创建多数类型的图表,如条形图,散点图,条形图,饼图,堆叠图,3D 图和地图图表。并且可以对图片进行调整并且保存。既然是可视化工具,就不过多介绍让我们直接实战体验吧。可能还会用到Python的一个第三方科学计算库numpy,其功能主要是对向量的一些科学计算,只会用到比较简单的计算。

实战演练

准备工作

安装matplotlib非常方便,Python3自带pip直接如下安装即可:

pip install matplotlib

安装完成后需要引入模块如下,我们习惯将numpy别名为np,matplotlib别名为plt,为了节省篇幅就不重复导入了

import matplotlib.pyplot as plt
import numpy as np

直线

首先我们构造出想画出的向量,然后调用plt.plot()绘制,通过plt.show()展现出来,如果想直接保存到本地可以加上plt.savefig()方法。让我们从画一条线开始吧。

x = np.array([1, 2, 3])
plt.plot(x)
plt.show()
line1.png

这个库用起来真的很简单,我们试试画两条线并且再添加一些说明信息

x = np.array([1, 2, 3])
y = np.array([5, 6, 7])
plt.plot(x, label='first line')
plt.plot(y, label='second line')
# 横坐标注释
plt.xlabel('Plot Number')
# 列坐标注释
plt.ylabel('Important var')
# 生成表标题
plt.title('Matplotlib demo\nCheck it out')
# 生成小方块显示每条线对应的label
plt.legend()
plt.show()
twoline.png

条形图

one = np.array([[1, 3, 5, 7, 9], [3, 4, 6, 12, 7]])
two = np.array([[2, 4, 6, 8, 10], [4, 2, 9, 8, 11]])
# 参数1是横坐标,参数2是高度
plt.bar(one[0], one[1], label='first')
plt.bar(two[0], two[1], label='second')
plt.xlabel('bar-hist Number')
# 列坐标注释
plt.ylabel('bar-hist height')
# 生成表标题
plt.title('Matplotlib demo\nCheck it out')
# 生成小方块显示每条线对应的label
plt.legend()
plt.show()
bar1.png

直方图

# 原始数据
population_ages = [22, 55, 62, 45, 21, 22, 34, 42, 42, 4, 99, 102, 110, 120, 121, 122, 130, 111, 115, 112, 80, 75, 65,
                   54, 44, 43, 42, 48, 12, 32, 44, 9, 7]
# 横坐标,表示增量
bins = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130]
plt.hist(population_ages, bins, histtype='bar', rwidth=0.8)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Matplotlib demo\nCheck it out')
plt.show()
hist1.png

散点图

data = np.array([[1, 2], [2, 3], [5, 6]])
# marker有许多图标:https://matplotlib.org/api/markers_api.html
plt.scatter(data[:, 0], data[:, 1], label='skitscat', color='k', s=25, marker="o")
plt.xlabel('x')
plt.ylabel('y')
plt.title('Matplotlib demo\nCheck it out')
plt.legend()
plt.show()
scatter1.png

堆叠图

days = [1, 2, 3, 4, 5]
sleeping = [7, 8, 6, 11, 7]
eating = [2, 3, 4, 3, 2]
working = [7, 8, 7, 2, 2]
playing = [8, 5, 7, 8, 13]

plt.plot([], [], color='m', label='Sleeping', linewidth=2)
plt.plot([], [], color='c', label='Eating', linewidth=2)
plt.plot([], [], color='r', label='Working', linewidth=2)
plt.plot([], [], color='k', label='Playing', linewidth=2)

plt.stackplot(days, sleeping, eating, working, playing, colors=['m',
                                                                'c', 'r', 'k'])
plt.xlabel('x')
plt.ylabel('y')
plt.title('Matplotlib demo\nCheck it out')
plt.legend()
plt.show()
stacked1.png

饼图

slices = [7, 2, 5, 11]
activities = ['sleeping', 'eating', 'working', 'playing']
cols = ['c', 'm', 'r', 'b']
# slices是切片比例,startangle是起始角度,explode可以拿出不是0的切片
plt.pie(slices,
        labels=activities,
        colors=cols,
        startangle=90,
        shadow=True,
        explode=(0, 0.1, 0, 0),
        autopct='%1.1f%%')
plt.title('Matplotlib demo\nCheck it out')
plt.show()
pie1.png

文件中加载数据

"""
test1.txt 内容格式如下
0   0
1  1
2  12
3  11
4  15
5  18
6  9
7  5
8  2
9  16
...
"""
data = np.loadtxt('../data/test1.txt', unpack=True)
plt.plot(data[0], data[1], label='Loaded from local file')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Matplotlib demo\nCheck it out')
plt.legend()
plt.show()
loaddata1.png

样式

style.use('fivethirtyeight')
fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(212)
data = np.loadtxt('../data/test1.txt', unpack=True)
ax1.plot(data[0], data[1])
ax2.plot(data[0], data[1])
ax3.plot(data[0], data[1])
plt.xlabel('x')
plt.ylabel('y')
plt.show()
style1.png

子图

style.use('ggplot')
# 创建子图,1*1网格,起点(0,0)
fig = plt.figure()
ax1 = plt.subplot2grid((1, 1), (0, 0))
ax1.xaxis.label.set_color('c')
ax1.yaxis.label.set_color('r')
# 数轴距离
ax1.set_yticks([0, 1.5, 2.5, 3.5])
data = np.array([[1, 2], [3, 4]])
# 填充
ax1.fill_between([0, 1], 0, [0, 1])
# 改边框
ax1.spines['left'].set_color('c')
ax1.spines['left'].set_linewidth(5)
ax1.spines['right'].set_visible(False)
ax1.spines['top'].set_visible(False)
ax1.tick_params(axis='x', colors='#f06215')
plt.plot(data)
plt.xlabel('Plot Number')
plt.ylabel('Important var')
plt.title('Matplotlib demo\nCheck it out')
plt.show()
![3d1.png](https://upload-images.jianshu.io/upload_images/13674655-b8ffc10cee4a21d2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

3D图

style.use('ggplot')
fig = plt.figure()
ax1 = fig.add_subplot(111, projection='3d')
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [5, 6, 7, 8, 2, 5, 6, 3, 7, 2]
z = [1, 2, 6, 3, 2, 7, 3, 3, 7, 2]
x2 = [-1, -2, -3, -4, -5, -6, -7, -8, -9, -10]
y2 = [-5, -6, -7, -8, -2, -5, -6, -3, -7, -2]
z2 = [1, 2, 6, 3, 2, 7, 3, 3, 7, 2]
ax1.scatter(x, y, z, c='g', marker='o')
ax1.scatter(x2, y2, z2, c='r', marker='o')
ax1.set_xlabel('x axis')
ax1.set_ylabel('y axis')
ax1.set_zlabel('z axis')
plt.show()
3d1.png
style.use('fivethirtyeight')
fig = plt.figure()
ax1 = fig.add_subplot(111, projection='3d')
x = np.array([[1, 2, 3], [5, 6, 7]])
y = np.array([[5, 6, 7], [5, 2, 4]])
z = np.array([[1, 2, 6], [1, 2, 9]])
ax1.plot_wireframe(x, y, z)
ax1.set_xlabel('x axis')
ax1.set_ylabel('y axis')
ax1.set_zlabel('z axis')
plt.show()
3d2.png

动态图

style.use('fivethirtyeight')
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)

def animal1(i):
    data = np.loadtxt('../data/animal.txt', unpack=True)
    ax1.clear()
    ax1.plot(data[0], data[1])

ani = animation.FuncAnimation(fig, animal1, interval=1000)
plt.show()

动态向文件中写入数据可以监控显示数据变化

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,589评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,615评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,933评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,976评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,999评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,775评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,474评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,359评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,854评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,007评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,146评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,826评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,484评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,029评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,153评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,420评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,107评论 2 356

推荐阅读更多精彩内容