当前位置: 首页 > news >正文

matplotlib 文档:Pyplot tutorial

Pyplot tutorial

对pyplot 接口的介绍

简介

matplotlib.pyplot 是一堆函数的集成,让matplotlib 像MATLAB 一样使用。创建画布,画线,装饰啥的。

但是 pyplot API 没有面向对象的API 灵活。

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])      # 生成一个可视化的图是非常容易的
plt.ylabel('some data')
plt.show()# 注意一下坐标轴,当只传入一个列表或数组,matplotlib就认为这是y 值得序列,然后自动生成x 的值。
# 生成的x 的值是从0开始的,所以 y 1-4 x 0-3 
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])

格式化绘图

除了 x,y 两个参数,还有格式化字符串这个参数,来表示颜色和绘制的线的种类。默认是 ‘b-’ ,蓝色的实线。更多格式,,这些函数的参数也太多了。。。

plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro')    # 红点
plt.axis([0, 6, 0, 20])    # 这个函数指定了两个坐标的可视化范围
plt.show()import numpy as np
t = np.arange(0., 5., 0.2)    # 传入列表再内部也会转换成数组。# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')    # 不同格式再一个函数里画
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']) * 100plt.scatter('a', 'b', c='c', s='d', data=data)   # 指定了data 这个参数
plt.xlabel('entry a')              # 就可以使用相关联的字符串
plt.ylabel('entry b')			# c 颜色, s 标记点的大小
plt.show()

用分类数据绘图

names = ['group_a', 'group_b', 'group_c']
values = [1, 10, 100]plt.figure(figsize=(9, 3))plt.subplot(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()

在这里插入图片描述

控制线的属性

宽度,样式,抗锯齿等,设置方法:

  1. plt.plot(x,y, linewidth = 2.0) 通过关键字参数

  2. line, = plt.plot(x, y, '-'); line.set_antialiased(False) # turn off 抗锯齿 通过Line2D 对象的set 方法,plot 返回的是 Line2D 对象的列表。

  3. setp 方法

lines = plt.plot(x1, y1, x2, y2)
# use keyword args
plt.setp(lines, color='r', linewidth=2.0)
# or MATLAB style string value pairs
plt.setp(lines, 'color', 'r', 'linewidth', 2.0)

一下就是可用的 Line2D 属性:

  1. PropertyValue Type
    alphafloat
    animated[True | False]
    antialiased or aa[True | False]
    clip_boxa matplotlib.transform.Bbox instance
    clip_on[True | False]
    clip_patha Path instance and a Transform instance, a Patch
    color or cany matplotlib color
    containsthe hit testing function
    dash_capstyle['butt' | 'round' | 'projecting']
    dash_joinstyle['miter' | 'round' | 'bevel']
    dashessequence of on/off ink in points
    data(np.array xdata, np.array ydata)
    figurea matplotlib.figure.Figure instance
    labelany string
    linestyle or ls[ '-' | '--' | '-.' | ':' | 'steps' | …]
    linewidth or lwfloat value in points
    marker[ '+' | ',' | '.' | '1' | '2' | '3' | '4' ]
    markeredgecolor or mecany matplotlib color
    markeredgewidth or mewfloat value in points
    markerfacecolor or mfcany matplotlib color
    markersize or msfloat
    markevery[ None | integer | (startind, stride) ]
    pickerused in interactive line selection
    pickradiusthe line pick selection radius
    solid_capstyle['butt' | 'round' | 'projecting']
    solid_joinstyle['miter'| 'round' | 'bevel']
    transforma matplotlib.transforms.Transform instance
    visible[True | False]
    xdatanp.array
    ydatanp.array
    zorderany number
lines = plt.plot([1, 2, 3])
plt.step(lines)     # 获取可设置的线的属性列表(不是这个对象的取值)。。蛮方便的啊

使用多个图形和轴

绘图中,所有的函数都是i针对当前的图和轴,可以使用 Axes.gca 得到当前的轴, gcf 得到当前的图,一般不用管,交给后台就行

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()    # 也可以不用这个,因为figure(1) 会默认创建。
plt.subplot(211)     # 选择绘制的子图,两行一列第一个
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')plt.subplot(212)   # 也可以写成( 2, 1, 2)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()# 也可以创建多个 figure
import matplotlib.pyplot as plt
plt.figure(1)                # the first figure
plt.subplot(211)             # the first subplot in the first figure
plt.plot([1, 2, 3])
plt.subplot(212)             # the second subplot in the first figure
plt.plot([4, 5, 6])plt.figure(2)                # a second figure
plt.plot([4, 5, 6])          # creates a subplot(111) by defaultplt.figure(1)                # figure 1 current; subplot(212) still current
plt.subplot(211)             # make subplot(211) in figure1 current
plt.title('Easy as 1, 2, 3') # subplot 211 title

可以使用 pyplot.clf() or cla() 来清除当前的 figure 和 axes。如果你制作了大量的图形,注意再图形通过 close() 关闭前,其内存是不会释放的 matplotlib.pyplot.close(fig=None)

文本

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$')   # 支持 TeX 方程表达式
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()# 这些文本函数都是 text.Text 实例,可用定义属性
t = plt.xlabel('my data', fontsize=14, color='red')  # or setp() 

标记文本

使用 annotate 方法来标注文本,有两个位置 标志位置 (x,y) 和文本位置 (xtext, ytext)。

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()

在这里插入图片描述

对数和其他非线性轴

不仅支持线性轴刻度,也支持对数 和 log 的刻度,如果数据跨越很多数量级,就可以改变轴的比率。plt.xscale(‘log’)

# Fixing random state for reproducibility
np.random.seed(19680801)# make up some data in the open 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()# 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', linthresh=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)
# 调整子图布局,因为logit可能会占用更多空间
# 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()

在这里插入图片描述


http://www.taodudu.cc/news/show-6309515.html

相关文章:

  • 【physx/wasm】在physx中添加自定义接口并重新编译wasm
  • excel---常用操作
  • Lora训练Windows[笔记]
  • linux基础指令讲解(ls、pwd、cd、touch、mkdir)
  • InnoDB 事务处理机制
  • 启明云端ESP32 C3 模组WT32C3通过 MQTT 连接 AWS
  • 【python数据可视化笔记】——matplotlib.pyplot()
  • 逻辑回归python正则化 选择参数_SKlearn_逻辑回归小练习
  • python常用可视化技巧
  • Matplotlib官方文档学习笔记 PART1-简介 C2-pyplot教程 (19-12-4 by-xieyuxin)
  • 介绍一个使用 Go 语言开发的高性能可配置可扩展的日志库 logit
  • 机器学习:python常用可视化技巧
  • 学习C++该看什么书?
  • 学习c/c++ 推荐学习什么书籍?
  • C语言学习经典书籍推荐
  • Nginx安装和配置
  • 安装nginx配置
  • Liunx下Nginx安装配置
  • nginx安装配置 linux
  • Nginx 的安装配置
  • 安装 配置 Nginx
  • nginx 安装,配置
  • nginx安装配置(图文教程)
  • nginx安装配置、Nginx支持php
  • 虚拟机的Nginx安装配置
  • Linux Nginx安装配置及HTTPS配置
  • nginx安装配置记录
  • Nginx安装配置及使用方法
  • windows2008 没有本地用户和组
  • 计算机管理没有本地用户和组控制面板,win10管理没有本地用户和组怎么办_win10电脑管理没有本地用户和组解决方法...
  • 2003server计算机管理里面没有本地用户和组
  • win11本地用户和组找不到的解决办法
  • vue移动端手机号正则表达式
  • JavaScript实现11位手机号码正则表达式
  • SQL 数据初级查询—实验报告
  • SQL 使用记录