matplotlib教程学习笔记

pyplot 介绍

import matplotlib.pyplot as plt
import numpy as np
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()

  • 注意:pyplot的函数往往也是对象的函数
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot([1, 2, 3, 4])
ax2.plot([2, 3, 4, 5])
#ax1.ylabel("...") 没有这个方法。。。
#fig.show()会显示non-GUI-backend而不能执行, 而ax1.show() 或者ax2.show(),没有该方法
#估计得通篇看完再能窥其门径了

从上面的例子可以看出,纵坐标是我们给的数据,而横坐标,pyplot会自动从0给予编号。

plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.show()

修饰你的图案

pyplot格式继承自matlab(我不知道)。plot的第三个可选参数是一个格式字符串,代表颜色和曲线的种类,默认为"b-"。

plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro') #'ro' : red circles 红色的圆
plt.axis([0, 6, 0, 20]) # [xmin, xmax, ymin, ymax]
plt.show()

格式字符串 [color][marker][line]

fmt = ‘[color][marker][line]’

Colors

当格式字符串只限制颜色的时候,你可以写颜色的全称,也可以用16进制来表达。

或者任意的matplotlib.colors

plt.plot([1, 2, 3, 4], [1, 4, 9, 16], '#FF0000')
plt.axis([0, 6, 0, 20])
plt.show()

Markers

Line Styles

plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'g*--') #绿色 * 虚线
plt.axis([0, 6, 0, 20])
plt.show()

利用关键字作图(大概是数据映射到属性吧)

data = {'a': np.arange(50),
        'c': np.random.randint(0, 50, 50),
        'd': np.random.randn(50)}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100

plt.scatter('a', 'b', c='c', s='d', data=data)
plt.xlabel('entry a')
plt.ylabel('entry b')
plt.show()

传入类别

names = ['group_a', 'group_b', 'group_c']
values = [1, 10, 100]

plt.figure(1, figsize=(9, 3)) #figsize: 长9个单位,高3个单位

plt.subplot(131)  #131
plt.bar(names, values)
plt.subplot(132)
plt.scatter(names, values)
plt.subplot(133)
plt.plot(names, values)
plt.suptitle('Categorical Plotting')
plt.show()

控制线的属性

线有许多属性,比如线的宽度,虚线的形式等等。

我们有很多方法来设置线的属性:

plt.plot(x, y, linewidth=2.0)

使用line2D对象的setter方法也可以完成。

x1 = np.array([1, 2, 3, 4])
y1 = x1 ** 2
x2 = np.array([4, 3, 2, 1])
y2 = np.sin(x2)
line1, line2 = plt.plot(x1, y1, x2, y2)
line1.set_antialiased(False) #关闭抗锯齿
line2.set_linewidth(5.0)
plt.show()

使用setp()指令同样能够办到,这玩意儿还会返回图片的各种属性。

x1 = np.array([1, 2, 3, 4])
y1 = x1 ** 2
x2 = np.array([4, 3, 2, 1])
y2 = np.sin(x2)
lines = plt.plot(x1, y1, x2, y2)
plt.setp(lines, color='r', linewidth=2.0)

Line2D的属性

pro1 = {
       'alpha':0.2,
       'animated':True, #动画?啥效果?
       'antialiased':True,#抗锯齿 默认为True
       'color': 'red',
       'dash_capstyle': 'butt', #不知道干啥的  包裹起来?
       'dash_joinstyle': 'miter', #不知道干啥的
       'label': "会出现吗?",
       'linestyle': 'steps',
       #'lod': True 为啥没这属性
       'marker': '+',
       'markeredgecolor': 'red', #断点的颜色?
       'markeredgewidth': 2.0, #断点的大小
       'markerfacecolor': 'yellow',
       'markersize': 6.0 #这个是那个断点的大小,可是是什么压制了它的洪荒之力

       }
pro2 = {
        'alpha':0.8,
        'animated':False,
        'aa':False,
        'c': '#00FF00',
        'linestyle': '--',
        'marker': '1',
        'mec': 'blue',
        'mew': 3.0,
        'mfc': 'yellow', #啥意思啊,嵌了一层黄色
        'ms': 2.0

        }
x1 = np.arange(20)
y1 = x1
x2 = np.linspace(0, 20, 50)
y2 = np.sin(x2)
line1, line2 = plt.plot(x1, y1, x2, y2)
# use keyword args
plt.setp(line1, **pro1)
plt.setp(line2, **pro2)
plt.show()

操作多figures和axes

matlab和pyplot都有当前figure,axes的概念,所有画图操作都会应用到当前的axes上。函数gca()会返回当前的axes对象,而gcf()会返回当前figure对象。

def f(t):
    return np.exp(-t) * np.cos(2*np.pi*t)

t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)

plt.figure(1)
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')

plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()

subplot(mnk)

m: numrows

n: numcols

k: plot_numer [1-m*n]

就相当于把一块画布割成m行n列,即有mn块小区域,k就是我们要子图所放的区域的标识,从1到mn。而且,从下面的例子中可以看出,位置是从上到下,从左往右标号的。

def f(t):
    return np.exp(-t) * np.cos(2*np.pi*t)

t1 = np.arange(0.0, 5.0, 0.1)

plt.figure(1)
plt.subplot(221)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')

plt.subplot(222)
plt.plot(t1, f(t1), 'ro', t2, f(t2), 'k')

plt.subplot(223)
plt.plot(t1, f(t1), 'go', t2, f(t2), 'k')
plt.subplot(224)

plt.plot(t1, f(t1), 'yo', t2, f(t2), 'k')
plt.show()

clf()清空当前figure, cla()情况当前axes.

另外,figure所占内存,只用当调用close()的时候才会完全释放。

加入Text

text() :可将文本加入至任意位置

xlabel(), ylabel(), title() :加入至固定位置

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

# the histogram of the data
n, bins, patches = plt.hist(x, 50, density=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$')
#r表示原始字符串,否则得这么写plt.text(60, .025, '$\\mu=100,\ \\sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()

Annotating text

annoate()


ax = plt.subplot(111)

t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)

plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
             arrowprops=dict(facecolor='black', shrink=0.05),
             )

plt.ylim(-2, 2)
plt.show()

非线性axes

pyplot提供非线性标度,如对数化等等。(纵坐标好像还是原来的y,只是图像变了)

from matplotlib.ticker import NullFormatter  # useful for `logit` scale

# Fixing random state for reproducibility
np.random.seed(19680801)

# make up some data in the interval ]0, 1[
y = np.random.normal(loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)]
y.sort()
x = np.arange(len(y))

# plot with various axes scales
plt.figure(1)

# linear
plt.subplot(221)
plt.plot(x, y)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)

# log
plt.subplot(222)
plt.plot(x, y)
plt.yscale('log')
plt.title('log')
plt.grid(True)

# symmetric log
plt.subplot(223)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthreshy=0.01)
plt.title('symlog')
plt.grid(True)

# logit
plt.subplot(224)
plt.plot(x, y)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)
# Format the minor tick labels of the y-axis into empty strings with
# `NullFormatter`, to avoid cumbering the axis with too many labels.
plt.gca().yaxis.set_minor_formatter(NullFormatter())
# Adjust the subplot layout, because the logit one may take more space
# than usual, due to y-tick labels like "1 - 10^{-3}"
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,
                    wspace=0.35)

plt.show()

matplotlib 入门之Pyplot tutorial的更多相关文章

  1. matplotlib 入门之Image tutorial

    文章目录 载入图像为ndarray 显示图像 调取各个维度 利用cmp 获得像素点的RGB的统计 通过clim来限定rgb 标度在下方 插值,马赛克,虚化 matplotlib教程学习笔记 impor ...

  2. 绘图神器-matplotlib入门

    这次,让我们使用一个非常有名且十分有趣的玩意儿来完成今天的任务,它就是jupyter. 一.安装jupyter matplotlib入门之前,先安装好jupyter.这里只提供最为方便快捷的安装方式: ...

  3. Python 绘图库Matplotlib入门教程

    0 简单介绍 Matplotlib是一个Python语言的2D绘图库,它支持各种平台,并且功能强大,能够轻易绘制出各种专业的图像. 1 安装 pip install matplotlib 2 入门代码 ...

  4. Matplotlib 入门

    章节 Matplotlib 安装 Matplotlib 入门 Matplotlib 基本概念 Matplotlib 图形绘制 Matplotlib 多个图形 Matplotlib 其他类型图形 Mat ...

  5. Sahi (1) —— 快速入门(101 Tutorial)

    Sahi (1) -- 快速入门(101 Tutorial) jvm版本: 1.8.0_65 sahi版本: Sahi Pro 6.1.0 参考来源: Sahi官网 Sahi Quick Tutori ...

  6. python数据可视化——matplotlib 用户手册入门:pyplot 画图

    参考matplotlib官方指南: https://matplotlib.org/tutorials/introductory/pyplot.html#sphx-glr-tutorials-intro ...

  7. matplotlib 入门之Sample plots in Matplotlib

    文章目录 Line Plot One figure, a set of subplots Image 展示图片 展示二元正态分布 A sample image Interpolating images ...

  8. Pyplot tutorial,Pyplot官方教程自翻译

      matplotlib.pyplot is a collection of command style functions that make matplotlib work like MATLAB ...

  9. IPython绘图和可视化---matplotlib 入门

    最近总是需要用matplotlib绘制一些图,由于是新手,所以总是需要去翻书来找怎么用,即使刚用过的,也总是忘.所以,想写一个入门的教程,一方面帮助我自己熟悉这些函数,另一方面有比我还小白的新手可以借 ...

随机推荐

  1. 排序算法----快速排序java

    快速排序是对冒泡排序的一种改进,平均时间复杂度是O(nlogn) import java.util.Arrays; import java.util.Scanner; public class tes ...

  2. linux下objdump应用

    <a href="http://www.maomao365.com/?p=952" > linux命令objdump的用法  http://www.maomao365. ...

  3. SQL SERVER 查询表的各字段长度

    SELECT a.name,b.name,c.DATA_TYPE,b.max_length FROM sys.tables a join sys.columns b on b.object_id = ...

  4. SQL Server 索引重建手册

    注意: 索引重建前建议把数据库切换为完整模式,否则索引复制会在数据文件中进行,导致数据文件很大,而数据文件的收缩比日志文件的收缩要困难的多,且会对业务造成影响. 步骤一: 查询索引碎片,脚本如下,库比 ...

  5. python列表与元组的用法

    python列表与元组的用法 目录: 列表的用法: 1.增   append   +    extend 2.删  del    remove 3.改   insert 4.查  index 5.反向 ...

  6. LeetCode算法题-Add Binary(Java实现)

    这是悦乐书的第157次更新,第159篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第16题(顺位题号是67).给定两个二进制字符串,返回它们的总和(也是二进制字符串).输 ...

  7. 对于coursera上三门北大网课的评测

    今年暑假开始就选了coursera上三门北大的网课——C++程序设计.算法基础.数据结构基础,它们属于一个项目的,上的话每个月249块钱,项目里包括这三门一共有七门课.因为一开始是三门课同时上的,数据 ...

  8. 【大数据技术】Flink

    “下一代大数据处理引擎王者” Apache Flink 它既能保证数据一致性“Exactly Once",又能实时快速的处理海量数据.与生俱来的 Watermark 功能让它能对复杂数据乱序 ...

  9. 【NOI2019模拟】搬砖

    [NOI2019模拟]搬砖 Description 小火车很穷,只好去搬砖了. 小火车被工头要求搭建\(n\)座塔,第i个高度为\(H_i\),也就是由\(H_i\)块砖头组成.每次小火车可以携带至多 ...

  10. go语言中如何模拟100个IP同时并发访问服务器,每个ip要重复访问1000次。每个Ip一分钟之内只能访问一次

    package main import ( "time" "sync" "fmt" "sync/atomic" ) ty ...