-
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')
标记 | 符号 | 描述 |
---|---|---|
"." | | 点 |
"," | | 像素点 |
"o" | | 实心圆 |
"v" | | 下三角 |
"^" | | 上三角 |
"<" | | 左三角 |
">" | | 右三角 |
"1" | | 下三叉 |
"2" | | 上三叉 |
"3" | | 左三叉 |
"4" | | 右三叉 |
"8" | | 八角形 |
"s" | | 正方形 |
"p" | | 五边形 |
"P" | | 加号(填充) |
"*" | | 星号 |
"h" | | 六边形 1 |
"H" | | 六边形 2 |
"+" | | 加号 |
"x" | | 乘号 x |
"X" | | 乘号 x (填充) |
"D" | | 菱形 |
"d" | | 瘦菱形 |
"|" | | 竖线 |
"_" | | 横线 |
0 (TICKLEFT) | | 左横线 |
1 (TICKRIGHT) | | 右横线 |
2 (TICKUP) | | 上竖线 |
3 (TICKDOWN) | | 下竖线 |
4 (CARETLEFT) | | 左箭头 |
5 (CARETRIGHT) | | 右箭头 |
6 (CARETUP) | | 上箭头 |
7 (CARETDOWN) | | 下箭头 |
8 (CARETLEFTBASE) | | 左箭头 (中间点为基准) |
9 (CARETRIGHTBASE) | | 右箭头 (中间点为基准) |
10 (CARETUPBASE) | | 上箭头 (中间点为基准) |
11 (CARETDOWNBASE) | | 下箭头 (中间点为基准) |
"None", " " or "" | 没有任何标记 | |
'$...$' | | 渲染指定的字符。例如 "$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,值可以是浮点数,如:1、2.0、5.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()
颜色条参数值可以是以下值:
颜色名称 | 保留关键字 | |
---|---|---|
Accent | Accent_r | |
Blues | Blues_r | |
BrBG | BrBG_r | |
BuGn | BuGn_r | |
BuPu | BuPu_r | |
CMRmap | CMRmap_r | |
Dark2 | Dark2_r | |
GnBu | GnBu_r | |
Greens | Greens_r | |
Greys | Greys_r | |
OrRd | OrRd_r | |
Oranges | Oranges_r | |
PRGn | PRGn_r | |
Paired | Paired_r | |
Pastel1 | Pastel1_r | |
Pastel2 | Pastel2_r | |
PiYG | PiYG_r | |
PuBu | PuBu_r | |
PuBuGn | PuBuGn_r | |
PuOr | PuOr_r | |
PuRd | PuRd_r | |
Purples | Purples_r | |
RdBu | RdBu_r | |
RdGy | RdGy_r | |
RdPu | RdPu_r | |
RdYlBu | RdYlBu_r | |
RdYlGn | RdYlGn_r | |
Reds | Reds_r | |
Set1 | Set1_r | |
Set2 | Set2_r | |
Set3 | Set3_r | |
Spectral | Spectral_r | |
Wistia | Wistia_r | |
YlGn | YlGn_r | |
YlGnBu | YlGnBu_r | |
YlOrBr | YlOrBr_r | |
YlOrRd | YlOrRd_r | |
afmhot | afmhot_r | |
autumn | autumn_r | |
binary | binary_r | |
bone | bone_r | |
brg | brg_r | |
bwr | bwr_r | |
cividis | cividis_r | |
cool | cool_r | |
coolwarm | coolwarm_r | |
copper | copper_r | |
cubehelix | cubehelix_r | |
flag | flag_r | |
gist_earth | gist_earth_r | |
gist_gray | gist_gray_r | |
gist_heat | gist_heat_r | |
gist_ncar | gist_ncar_r | |
gist_rainbow | gist_rainbow_r | |
gist_stern | gist_stern_r | |
gist_yarg | gist_yarg_r | |
gnuplot | gnuplot_r | |
gnuplot2 | gnuplot2_r | |
gray | gray_r | |
hot | hot_r | |
hsv | hsv_r | |
inferno | inferno_r | |
jet | jet_r | |
magma | magma_r | |
nipy_spectral | nipy_spectral_r | |
ocean | ocean_r | |
pink | pink_r | |
plasma | plasma_r | |
prism | prism_r | |
rainbow | rainbow_r | |
seismic | seismic_r | |
spring | spring_r | |
summer | summer_r | |
tab10 | tab10_r | |
tab20 | tab20_r | |
tab20b | tab20b_r | |
tab20c | tab20c_r | |
terrain | terrain_r | |
twilight | twilight_r | |
twilight_shifted | twilight_shifted_r | |
viridis | viridis_r | |
winter | winter_r |