matplotlib 入门之Pyplot tutorial
文章目录
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
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的更多相关文章
- matplotlib 入门之Image tutorial
文章目录 载入图像为ndarray 显示图像 调取各个维度 利用cmp 获得像素点的RGB的统计 通过clim来限定rgb 标度在下方 插值,马赛克,虚化 matplotlib教程学习笔记 impor ...
- 绘图神器-matplotlib入门
这次,让我们使用一个非常有名且十分有趣的玩意儿来完成今天的任务,它就是jupyter. 一.安装jupyter matplotlib入门之前,先安装好jupyter.这里只提供最为方便快捷的安装方式: ...
- Python 绘图库Matplotlib入门教程
0 简单介绍 Matplotlib是一个Python语言的2D绘图库,它支持各种平台,并且功能强大,能够轻易绘制出各种专业的图像. 1 安装 pip install matplotlib 2 入门代码 ...
- Matplotlib 入门
章节 Matplotlib 安装 Matplotlib 入门 Matplotlib 基本概念 Matplotlib 图形绘制 Matplotlib 多个图形 Matplotlib 其他类型图形 Mat ...
- Sahi (1) —— 快速入门(101 Tutorial)
Sahi (1) -- 快速入门(101 Tutorial) jvm版本: 1.8.0_65 sahi版本: Sahi Pro 6.1.0 参考来源: Sahi官网 Sahi Quick Tutori ...
- python数据可视化——matplotlib 用户手册入门:pyplot 画图
参考matplotlib官方指南: https://matplotlib.org/tutorials/introductory/pyplot.html#sphx-glr-tutorials-intro ...
- matplotlib 入门之Sample plots in Matplotlib
文章目录 Line Plot One figure, a set of subplots Image 展示图片 展示二元正态分布 A sample image Interpolating images ...
- Pyplot tutorial,Pyplot官方教程自翻译
matplotlib.pyplot is a collection of command style functions that make matplotlib work like MATLAB ...
- IPython绘图和可视化---matplotlib 入门
最近总是需要用matplotlib绘制一些图,由于是新手,所以总是需要去翻书来找怎么用,即使刚用过的,也总是忘.所以,想写一个入门的教程,一方面帮助我自己熟悉这些函数,另一方面有比我还小白的新手可以借 ...
随机推荐
- Django创建新项目
1.安装Django 终端中输入:pip install Django==2.1.4 等于号后面的为版本,选则适合自己python的版本,如下图 Django version Py ...
- java反射笔记
反射(reflect) 1. Class对象 1.1 什么是Class对象 当JVM加载某个class文件的时候,会自动创建一个唯一的Class对象(注意:由同一个类加载器加载的class文件),这个 ...
- iOS 键盘上方增加工具栏
UIToolbar *keyboardDoneButtonView = [[UIToolbar alloc] init]; [keyboardDoneButtonView sizeToFit]; UI ...
- 【PAT】B1010 一元多项式求导
这道题的用例中没有负数 在输入时就进行结果的计算,忽略常数项, 顺序输出 #include<cstdio> #include<vector> using namespace s ...
- hashcode相等两个类一定相等吗?equals呢?相反呢?
hashCode相等,equals也不一定相等, 两个类也不一定相等 equals相同, 说明是同一个对象, 那么hashCode一定相同 哈希表是结合了直接寻址和链式寻址两种方式,所需要的就是将需要 ...
- MySql 中文写入数据库乱码及Incorrect string value: '\xF0\x9F...' for column 'XXX' at row 1解决
一.中文写入乱码问题 我输入的中文编码是 urf8 的,建的库是 urf8 的,但是插入MySQL总是乱码,一堆"???????????????????????".可以使用以下的方 ...
- Servlet中的request与response
了解这方面的知识可以查看以下博客 https://www.cnblogs.com/zhangyinhua/p/7629221.html https://www.cnblogs.com/zhaojian ...
- Angular四大核心特性
Angular四大核心特性 Angular四大核心特性理论概述 MVC模式:它目的是为了分离视图.模型和控制器而设计出来的:其中数据模型用来储存数据,视图用来向用户展示应用程序,控制器充当模型和视图之 ...
- 【C编程基础】C程序常用函数
基础知识 1.const const 修饰的数据类型是指常类型,常类型的变量或对象的值是不能被更新的. ; 或 ; //在定义该const变量时,通常需要对它进行初始化,因为以后就没有机会再改变它了 ...
- 前端数据库——WebSQL和IndexedDB
一.WebSQL WebSQL是前端的一个独立模块,是web存储方式的一种,我们调试的时候会经常看到,只是一般很少使用.并且,当前只有谷歌支持,ie和火狐均不支持. 我们对数据库的一般概念是后端才会跟 ...