Matplotlib 学习笔记

  1. pyploy模块学习 

plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)

颜色字符:'b' 蓝色,'m' 洋红色,'g' 绿色,'y' 黄色,'r' 红色,'k' 黑色,'w' 白色,'c' 青绿色,'#008000' RGB 颜色符串

线型参数:'‐' 实线,'‐‐' 破折线,'‐.' 点划线,':' 虚线

标记字符:'.' 点标记,',' 像素标记(极小点),'o' 实心圈标记,'v' 倒三角标记,'^' 上三角标记,'>' 右三角标记,'<' 左三角标记..

fmt = '[marker][line][color]'

例如 plot(y, 'r+') # 使用红色 + 号

<import matplotlib.pyplot as plt
import numpy as np
#坐标为 (1, 3) 、 (2, 8) 、(6, 1) 、(8, 10),对应的两个数组为:[1, 2, 6, 8] 与 [3, 8, 1, 10]。
xpoints = np.array([1, 2, 6, 8])
ypoints = np.array([3, 8, 1, 10])
​
plt.plot(xpoints, ypoints,'r--o')
plt.show()

ypoints = np.array([3, 8, 1, 10, 5, 7])
​plt.plot(ypoints, 'r-.^')
plt.show()
​
import matplotlib
print(matplotlib.__version__)
import matplotlib.pyplot as plt
import numpy as np
​
​
if __name__ == '__main__':
    x = np.arange(0,4*np.pi,0.1)   # start,stop,step
    y = np.sin(x)
    z = np.cos(x)
    plt.plot(x,y,'b-.*',x,z ,'r--o')
    plt.show()
​


绘图标记

例如:plt.plot(ypoints, marker = 'o')

标记符号描述
"."

m00

","

m01

像素点
"o"

m02

实心圆
"v"

m03

下三角
"^"

m04

上三角
"<"

m05

左三角
">"

m06

右三角
"1"

m07

下三叉
"2"

m08

上三叉
"3"

m09

左三叉
"4"

m10

右三叉
"8"

m11

八角形
"s"

m12

正方形
"p"

m13

五边形
"P"

m23

加号(填充)
"*"

m14

星号
"h"

m15

六边形 1
"H"

m16

六边形 2
"+"

m17

加号
"x"

m18

乘号 x
"X"

m24

乘号 x (填充)
"D"

m19

菱形
"d"

m20

瘦菱形
"|"

m21

竖线
"_"

m22

横线
0 (TICKLEFT)

m25

左横线
1 (TICKRIGHT)

m26

右横线
2 (TICKUP)

m27

上竖线
3 (TICKDOWN)

m28

下竖线
4 (CARETLEFT)

m29

左箭头
5 (CARETRIGHT)

m30

右箭头
6 (CARETUP)

m31

上箭头
7 (CARETDOWN)

m32

下箭头
8 (CARETLEFTBASE)

m33

左箭头 (中间点为基准)
9 (CARETRIGHTBASE)

m34

右箭头 (中间点为基准)
10 (CARETUPBASE)

m35

上箭头 (中间点为基准)
11 (CARETDOWNBASE)

m36

下箭头 (中间点为基准)
"None", " " or ""没有任何标记
'$...$'

m37

渲染指定的字符。例如 "$f$" 以字母 f 为标记。

线类型:

线类型标记描述
'-'实线
':'虚线
'--'破折线
'-.'点划线

颜色类型:

颜色标记描述
'r'红色
'g'绿色
'b'蓝色
'c'青色
'm'品红
'y'黄色
'k'黑色
'w'白色

标记大小与颜色

我们可以自定义标记的大小与颜色,使用的参数分别是:

  • markersize,简写为 ms:定义标记的大小。

  • markerfacecolor,简写为 mfc:定义标记内部的颜色。

  • markeredgecolor,简写为 mec:定义标记边框的颜色。

例如: plt.plot(ypoints, marker = 'o', ms = 20)

plt.plot(x,y, marker = 'o', ms = 20, mec = 'r')

plt.plot(ypoints, marker = 'o', ms = 20, mec = '#4CAF50', mfc = '#4CAF50')

线的类型

线的类型可以使用 linestyle 参数来定义,简写为 ls

类型简写说明
'solid' (默认)'-'实线
'dotted'':'点虚线
'dashed''--'破折线
'dashdot''-.'点划线
'None''' 或 ' '不画线
eg. plt.plot(ypoints, linestyle = 'dotted')

线的颜色

线的颜色可以使用 color 参数来定义,简写为 c

颜色类型:

颜色标记描述
'r'红色
'g'绿色
'b'蓝色
'c'青色
'm'品红
'y'黄色
'k'黑色
'w'白色

线的宽度

线的宽度可以使用 linewidth 参数来定义,简写为 lw,值可以是浮点数,如:12.05.67 等。

eg.  plt.plot(ypoints, linewidth = '12.5')

多条线的绘制

import matplotlib.pyplot as plt
import numpy as np
​
y1 = np.array([3, 7, 5, 9])
y2 = np.array([6, 2, 13, 10])
​
plt.plot(y1)
plt.plot(y2)
​
plt.show()

Matplotlib 轴标签和标题

我们可以使用 xlabel()ylabel() 方法来设置 x 轴和 y 轴的标签。

import numpy as np
import matplotlib.pyplot as plt
​
x = np.array([1, 2, 3, 4])
y = np.array([1, 4, 9, 16])
plt.plot(x, y)
​
plt.title("TITLE")
plt.xlabel("x - label")
plt.ylabel("y - label")
​
plt.show()

标题

我们可以使用 title() 方法来设置标题。

matplotlib不支持中文,中文需要打补丁

标题与标签的定位

title() 方法提供了 loc 参数来设置标题显示的位置,可以设置为: 'left', 'right', 和 'center', 默认值为 'center'

xlabel() 方法提供了 loc 参数来设置 x 轴显示的位置,可以设置为: 'left', 'right', 和 'center', 默认值为 'center'

ylabel() 方法提供了 loc 参数来设置 y 轴显示的位置,可以设置为: 'bottom', 'top', 和 'center', 默认值为 'center'

查看系统字体

from matplotlib import pyplot as plt
import matplotlib
a=sorted([f.name for f in matplotlib.font_manager.fontManager.ttflist])
​
for i in a:
    print(i)

Matplotlib 网格线

matplotlib.pyplot.grid(b=None, which='major', axis='both', )

参数说明:

  • b:可选,默认为 None,可以设置布尔值,true 为显示网格线,false 为不显示,如果设置 **kwargs 参数,则值为 true。

  • which:可选,可选值有 'major'、'minor' 和 'both',默认为 'major',表示应用更改的网格线。

  • axis:可选,设置显示哪个方向的网格线,可以是取 'both'(默认),'x' 或 'y',分别表示两个方向,x 轴方向或 y 轴方向。

  • **kwargs:可选,设置网格样式,可以是 color='r', linestyle='-' 和 linewidth=2,分别表示网格线的颜色,样式和宽度。

plt.grid(axis='x',color = 'r', linestyle = '--', linewidth = 0.5)

Matplotlib 绘制多图

我们可以使用 pyplot 中的 subplot()subplots() 方法来绘制多个子图。

subpot() 方法在绘图时需要指定位置,subplots() 方法可以一次生成多个,在调用时只需要调用生成对象的 ax 即可。

subplot(nrows, ncols, index, **kwargs)
subplot(pos, **kwargs)
subplot(**kwargs)
subplot(ax)

以上函数将整个绘图区域分成 nrows 行和 ncols 列,然后从左到右,从上到下的顺序对每个子区域进行编号 1...N ,左上的子区域的编号为 1、右下的区域编号为 N,编号可以通过参数 index 来设置。

设置 numRows = 1,numCols = 2,就是将图表绘制成 1x2 的图片区域, 对应的坐标为:

plotNum = 1, 表示的坐标为(1, 1), 即第一行第一列的子图。

plotNum = 2, 表示的坐标为(1, 2), 即第一行第二列的子图。

plotNum = 3, 表示的坐标为(2, 1), 即第二行第一列的子图。

plotNum = 4, 表示的坐标为(2, 2), 即第二行第二列的子图。

#plot 1:
x = np.array([0, 6])
y = np.array([0, 100])
​
plt.subplot(2, 2, 1)
plt.plot(x,y)
plt.title("plot 1")
​
#plot 2:
x = np.array([1, 2, 3, 4])
y = np.array([1, 4, 9, 16])
​
plt.subplot(2, 2, 2)
plt.plot(x,y)
plt.title("plot 2")
​
#plot 3:
x = np.array([1, 2, 3, 4])
y = np.array([3, 5, 7, 9])
​
plt.subplot(2, 2, 3)
plt.plot(x,y)
plt.title("plot 3")
​
#plot 4:
x = np.array([1, 2, 3, 4])
y = np.array([4, 5, 6, 7])
​
plt.subplot(2, 2, 4)
plt.plot(x,y)
plt.title("plot 4")
​
plt.suptitle("Test")
plt.show()

subplots()

matplotlib.pyplot.subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)

参数说明:

  • nrows:默认为 1,设置图表的行数。

  • ncols:默认为 1,设置图表的列数。

  • sharex、sharey:设置 x、y 轴是否共享属性,默认为 false,可设置为 'none'、'all'、'row' 或 'col'。 False 或 none 每个子图的 x 轴或 y 轴都是独立的,True 或 'all':所有子图共享 x 轴或 y 轴,'row' 设置每个子图行共享一个 x 轴或 y 轴,'col':设置每个子图列共享一个 x 轴或 y 轴。

  • squeeze:布尔值,默认为 True,表示额外的维度从返回的 Axes(轴)对象中挤出,对于 N1 或 1N 个子图,返回一个 1 维数组,对于 N*M,N>1 和 M>1 返回一个 2 维数组。如果设置为 False,则不进行挤压操作,返回一个元素为 Axes 实例的2维数组,即使它最终是1x1。

  • subplot_kw:可选,字典类型。把字典的关键字传递给 add_subplot() 来创建每个子图。

  • gridspec_kw:可选,字典类型。把字典的关键字传递给 GridSpec 构造函数创建子图放在网格里(grid)。

  • *fig_kw:把详细的关键字参数传给 figure() 函数。

# 创建一些测试数据 
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
​
# 创建一个画像和子图 
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')
# 创建两个子图
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)
# 创建四个子图 
fig, axs = plt.subplots(2, 2, subplot_kw=dict(projection="polar"))
axs[0, 0].plot(x, y)
axs[1, 1].scatter(x, y)
​

# 共享 x 轴
plt.subplots(2, 2, sharex='col')
​
# 共享 y 轴
plt.subplots(2, 2, sharey='row')
​
# 共享 x 轴和 y 轴
plt.subplots(2, 2, sharex='all', sharey='all')
​
# 这个也是共享 x 轴和 y 轴
plt.subplots(2, 2, sharex=True, sharey=True)
​
# 创建10 张图,已经存在的则删除
fig, ax = plt.subplots(num=10, clear=True)
​
plt.show()

Matplotlib 散点图

pyplot 中的 scatter() 方法来绘制散点图。

matplotlib.pyplot.scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, *, edgecolors=None, plotnonfinite=False, data=None, **kwargs)

参数说明:

x,y:长度相同的数组,也就是我们即将绘制散点图的数据点,输入数据。

s:点的大小,默认 20,也可以是个数组,数组每个参数为对应点的大小。

c:点的颜色,默认蓝色 'b',也可以是个 RGB 或 RGBA 二维行数组。

marker:点的样式,默认小圆圈 'o'。

cmap:Colormap,默认 None,标量或者是一个 colormap 的名字,只有 c 是一个浮点数数组的时才使用。如果没有申明就是 image.cmap。

norm:Normalize,默认 None,数据亮度在 0-1 之间,只有 c 是一个浮点数的数组的时才使用。

vmin,vmax::亮度设置,在 norm 参数存在时会忽略。

alpha::透明度设置,0-1 之间,默认 None,即不透明。

linewidths::标记点的长度。

edgecolors::颜色或颜色序列,默认为 'face',可选值有 'face', 'none', None。

plotnonfinite::布尔值,设置是否使用非限定的 c ( inf, -inf 或 nan) 绘制点。

**kwargs::其他参数。

import matplotlib.pyplot as plt
import numpy as np
​
x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
y = np.array([1, 4, 9, 16, 7, 11, 23, 18])
#sizes = np.array([20,50,100,200,500,1000,60,90])
#plt.scatter(x, y, s=sizes)
​
#colors = np.array(["red","green","black","orange","purple","beige","cyan","magenta"])
#plt.scatter(x, y, c=colors)
​
#x = np.array([2,2,8,1,15,8,12,9,7,3,11,4,7,14,12])
#y = np.array([100,105,84,105,90,99,90,95,94,100,79,112,91,80,85])
#plt.scatter(x, y, color = '#88c999')
​
plt.scatter(x, y)
plt.show()

# 随机数生成器的种子
np.random.seed(19680801)
​
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = (30 * np.random.rand(N))**2  # 0 to 15 point radii
​plt.scatter(x, y, s=area, c=colors, alpha=0.5) # 设置颜色及透明度
​plt.title("Test") # 设置标题
​plt.show()

颜色条 Colormap

Matplotlib 模块提供了很多可用的颜色条。

颜色条就像一个颜色列表,其中每种颜色都有一个范围从 0 到 100 的值。

下面是一个颜色条的例子:

设置颜色条需要使用 cmap 参数,默认值为 'viridis',之后颜色值设置为 0 到 100 的数组。

import matplotlib.pyplot as plt
import numpy as np
​
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
colors = np.array([0, 10, 20, 30, 40, 45, 50, 55, 60, 70, 80, 90, 100])
​
plt.scatter(x, y, c=colors, cmap='viridis')
#换个颜色条参数, cmap 设置为 afmhot_r:
#plt.scatter(x, y, c=colors, cmap='afmhot_r')
​
plt.colorbar()
​
plt.show()

颜色条参数值可以是以下值:

颜色名称保留关键字
AccentAccent_r
BluesBlues_r
BrBGBrBG_r
BuGnBuGn_r
BuPuBuPu_r
CMRmapCMRmap_r
Dark2Dark2_r
GnBuGnBu_r
GreensGreens_r
GreysGreys_r
OrRdOrRd_r
OrangesOranges_r
PRGnPRGn_r
PairedPaired_r
Pastel1Pastel1_r
Pastel2Pastel2_r
PiYGPiYG_r
PuBuPuBu_r
PuBuGnPuBuGn_r
PuOrPuOr_r
PuRdPuRd_r
PurplesPurples_r
RdBuRdBu_r
RdGyRdGy_r
RdPuRdPu_r
RdYlBuRdYlBu_r
RdYlGnRdYlGn_r
RedsReds_r
Set1Set1_r
Set2Set2_r
Set3Set3_r
SpectralSpectral_r
WistiaWistia_r
YlGnYlGn_r
YlGnBuYlGnBu_r
YlOrBrYlOrBr_r
YlOrRdYlOrRd_r
afmhotafmhot_r
autumnautumn_r
binarybinary_r
bonebone_r
brgbrg_r
bwrbwr_r
cividiscividis_r
coolcool_r
coolwarmcoolwarm_r
coppercopper_r
cubehelixcubehelix_r
flagflag_r
gist_earthgist_earth_r
gist_graygist_gray_r
gist_heatgist_heat_r
gist_ncargist_ncar_r
gist_rainbowgist_rainbow_r
gist_sterngist_stern_r
gist_yarggist_yarg_r
gnuplotgnuplot_r
gnuplot2gnuplot2_r
graygray_r
hothot_r
hsvhsv_r
infernoinferno_r
jetjet_r
magmamagma_r
nipy_spectralnipy_spectral_r
oceanocean_r
pinkpink_r
plasmaplasma_r
prismprism_r
rainbowrainbow_r
seismicseismic_r
springspring_r
summersummer_r
tab10tab10_r
tab20tab20_r
tab20btab20b_r
tab20ctab20c_r
terrainterrain_r
twilighttwilight_r
twilight_shiftedtwilight_shifted_r
viridisviridis_r
winterwinter_r
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值