Python-包-可视化-matplotlib

绘图标记

通过marker可以指定绘制图形中所用标记的形状,比如
fmt 参数定义了基本格式,如标记、线条样式和颜色。
markersize,简写为 ms:定义标记的大小。
markerfacecolor,简写为 mfc:定义标记内部的颜色。
markeredgecolor,简写为 mec:定义标记边框的颜色。

1
2
3
4
5
6
7
8
9
10
11
import matplotlib.pyplot as plt
import numpy as np

ypoints = np.array([1,3,4,5,8,9,6,1,3,4,5,2,4])

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

plt.show()

点类型符号如下:

通过 markerfmt(同时指定线条样式和颜色) 指定:

1
2
plt.plot(ypoints, marker = 'o')
plt.plot(ypoints, fmt = 'o:r')

标记 描述
“.”
“,” 像素点
“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 为标记。

线类型如下

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

1
2
plt.plot(ypoints, linestyle = 'dotted')
plt.plot(ypoints, ls = '-.')

线类型标记 简写 描述
‘solid’ (默认) ‘-‘ 实线
‘dotted’ ‘:’ 虚线
‘dashed’ ‘–’ 破折线
‘dashdot’ ‘-.’ 点划线
‘None’ ‘’ 不画线

线条的粗细

线条的粗细直接使用 linewidth 定义。

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

颜色类型

通过 color 或 r指定

1
2
plt.plot(ypoints, color = 'r')
plt.plot(ypoints, c = '#8FBC8F')

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

指定图片的标题和标签

标题

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

1
plt.title("TEST TITLE",loc="left")

坐标轴

我们可以使用 xlabel()ylabel() 方法来设置 x 轴和 y 轴的标签。
xlabel() 方法提供了 loc 参数来设置 x 轴显示的位置,可以设置为: ‘left’, ‘right’, 和 ‘center’, 默认值为 ‘center’。
ylabel() 方法提供了 loc 参数来设置 y 轴显示的位置,可以设置为: ‘bottom’, ‘top’, 和 ‘center’, 默认值为 ‘center’。

1
2
plt.xlabel("x - label",loc="left")
plt.ylabel("y - label",loc="left")

中文支持

默认绘图时不支持中文的,如果要在绘图中显示中文,需要先导入字体,并设置字体。

1
2
3
4
5
6
7
8
9
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)

# 挑选要给中文字体加入绘图库
plt.rcParams['font.family']=['STFangsong']

网格线

一张图片绘制多图的排版

matplotlib 支持使用两种方式进行多子图的排版,分别是 pyplot 中的 subplot()subplots() 方法来绘制多个子图。

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

subplot()示例

1
2
3
4
5
subplot(nrows, ncols, index, **kwargs) # 前面两个参数是进行分区,index负责某一个子图的定位## subplots() 示例

subplot(pos, **kwargs)
subplot(**kwargs)
subplot(ax)

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

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

根据位置分别绘图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import matplotlib.pyplot as plt
import numpy as np

#plot 1:
xpoints = np.array([0, 6])
ypoints = np.array([0, 100])

plt.subplot(1, 2, 1)
plt.plot(xpoints,ypoints)
plt.title("plot 1")

#plot 2:
x = np.array([1, 2, 3, 4])
y = np.array([1, 4, 9, 16])

plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.title("plot 2")

plt.suptitle("RUNOOB subplot Test")
plt.show()

subplots() 示例

1
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() 函数。
1
2
3
4
5
6
7
8
9
fig, axes = plt.subplots(2, 2, sharex=True, sharey=True, figsize=(14, 8))
# 通过axes的索引定位绘制图片
axes[0, 0].plot(data)
axes[0, 1].bar(range(len(data)), data, color='k', alpha=0.5)
axes[1, 0].scatter(range(len(data)), data)
axes[1, 1].plot(data, 'c>--')
# 调节子图直接的距离
plt.subplots_adjust(wspace=0, hspace=0)
plt.show()

各类图标命令简介

折线图

1
2
3
4
5
6
7
8
9
10
11
#merged_df=pd.read_csv("./data/merged_df.csv")
plt.figure(figsize=[12,5])
color=['#A51C36','#84BA42','#7ABBDB','#682487','#9E9E9E','#DBB428']
for i in range(0,6):
plt.plot(merged_df.index,merged_df[merged_df.columns[i]],label=merged_df.columns[i],color=color[i])
plt.legend()
plt.xticks(rotation=45)
plt.xlabel("STRC")
plt.ylabel("Correlation(.corr())")

plt.show()

alt text

箱线图

1
2


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
plt.boxplot(x,                      # x:指定要绘制箱图的数据
notch=None, # notch:是否是凹口的形式展现箱线图,默认非凹口
sym=None, # sym:指定异常点的形状,默认为+号显示
vert=None, # vert:是否需要将箱线图垂直摆放,默认垂直摆放
whis=None, # whis:指定上下须与上下四分位的距离,默认为1.5倍的四分位差
positions=None, # positions:指定箱线图的位置,默认为[0,1,2…]
widths=None, # widths:指定箱线图的宽度,默认为0.5
patch_artist=None, # patch_artist:是否填充箱体的颜色
meanline=None, # meanline:是否用线的形式表示均值,默认用点来表示
showmeans=None, # showmeans:是否显示均值,默认不显示
showcaps=None, # showcaps:是否显示箱线图顶端和末端的两条线,默认显示
showbox=None, # showbox:是否显示箱线图的箱体,默认显示
showfliers=None, # showfliers:是否显示异常值,默认显示
boxprops=None, # boxprops:设置箱体的属性,如边框色,填充色等
labels=None, # labels:为箱线图添加标签,类似于图例的作用
flierprops=None, # filerprops:设置异常值的属性,如异常点的形状、大小、填充色等
medianprops=None, # medianprops:设置中位数的属性,如线的类型、粗细等
meanprops=None, # meanprops:设置均值的属性,如点的大小、颜色等
capprops=None, # capprops:设置箱线图顶端和末端线条的属性,如颜色、粗细等
whiskerprops=None) # whiskerprops:设置须的属性,如颜色、粗细、线的类型等

参考资料

  1. https://www.runoob.com/matplotlib/matplotlib-grid.html
-------------本文结束感谢您的阅读-------------