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. C#-委托(十七)

    概述 委托(Delegate) 是存有对某个方法的引用的一种引用类型变量 委托特别用于实现事件和回调方法.所有的委托都派生自 System.Delegate 类 委托是一个类,么它就可以被定义在任何地 ...

  2. WinServerDFS

    DFS提供共享路径统一命名,且文件相互备份,具有高可用性. 1.在相应的服务器上安装服务. --命名空间,复制以及管理控制台的安装 install-windowsfeature fs-dfs-name ...

  3. 孟岩:通证(token)和通证经济的目的在于改善现有经济的效率性

    孟岩是最早将token翻译成为通证的区块链大咖,这个翻译已经得到到了越来越人的认可.原来它叫代币,孟岩建议把它翻译成通证.以下是孟岩关于通证的注解. (孟岩,柏链道捷CEO,CSDN副总裁,区块链通证 ...

  4. c/c++ 标准库 map set 大锅炖

    标准库 map set 大锅炖 一,关联容器有哪些 按关键字有序保存元素 map 保存key和value set 只保存key mulutimap key可以重复出现 multiset key可以重复 ...

  5. JavaScript实现元素拖动性能优化

    前言:前几天没事干写了个小网站,打算用原生的javascript实现元素的拖动,但是事情并没有想象的那么顺利,首先是实现了拖动的元素卡的不能再卡,简直不能够,上图~~ 看见没?这就是效果,简直让人欲哭 ...

  6. 如何激活windows或office

    郑重承诺:该激活软件没有病毒,有任何侵害行为,找我QQ:122317653 Step one: 首先你需要安装KMS Auto Net激活器,但我们都知道一些杀毒软件都会将此类激活器警告成木马病毒,原 ...

  7. SSL 原理及 https 配置

    目录 1. SSL 原理 1.1. SSL 简介 1.2. 主要概念 1.3. 建立安全连接的过程 2. https 配置 (以 nginx 为例) SSL 原理 SSL 简介 SSL (Secure ...

  8. C# → 数据库

    Database: public static class dbconnection{ static string cons = "data source = (local) ;initia ...

  9. Java面试知识点之线程篇(二)

    前言:接上篇,这里继续对java线程相关知识点进行总结. 1.notify和notifyall的区别 notify()方法能够唤醒一个正在等待该对象的monitor的线程,当有多个线程都在等待该对象的 ...

  10. socket.setSoTimeout(1000);

    这个用来设置与socket的inputStream相关的read操作阻塞的等待时间,超过设置的时间了,假如还是阻塞状态,会抛出异常java.net.SocketTimeoutException: Re ...