matplotlib:plot相关、marker样式、线样式、Text样式

0、简介

matplotlib中有两种plot绘制折线的方式,分别是

matplotlib.axes.Axes.plot(……)
matplotlib.pyplot.plot(……)

这两者的作用都是绘制折线,参数也相同,区别在于绘制的位置Axes.plot用于在子画布上绘图,而pyplot.plot则是在总画布上绘图

比如我们有

fig, axs = plt.subplots(2, 2)  # 将一个画布分为2*2的子画布,子画布通过axs访问,总画布通过fig访问

这里的fig是总画布,axs子画布构成的ndarray,通过axs[i][j]就可以访问到具体的画布,再通过axs[i][j].plot(……)就能实现在这些子画布上操作的目的。

如果没有区分画布,则直接用pyplot.plot(……)即可

1、用法

1.1、基本用法

以上是这两种plot的区别,不过plot具体用法(即参数设置)相同,都是:

plot(*args, scalex=True, scaley=True, data=None, **kwargs)

这里就一并说明了。

该函数的作用是,用折线标识点(markers)绘制坐标对(x,y),这两种绘制方式的区别在于折线会把坐标对代表的点相连标识点则只绘制出坐标对代表的点(即一个是折线图,一个是点图)。

两种写法:

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

其中用[ ]框起来的项都是可以省略的项。

绘制出的点或者折线的节点坐标由x,y给出。

fmt是一个可选参数,可以用它来指定一些基本的样式——颜色、标识点样式、线型。以下代码记录了部分样式的写法(具体可以在下文Notes一节查找):

plot(x, y) #用默认线型、颜色绘制折线图
plot(x, y, 'bo') #用蓝色的圆点标识绘制点图
plot(y) #绘制折线图,x坐标用[0,1,...,N-1]表示
plot(y,'r+') #点图,x坐标同上,点样式为红色、+号

我们可以用Line2D的相关属性作为参数,在绘制时控制更多效果。Line属性fmt可以混用,以下代码给出了相同样式的两种不同代码写法:

plot(x, y, 'go--', linewidth=2, markersize=12)
plot(x, y, color='green', marker='o', linestyle='dashed',
     linewidth=2, markersize=12)

虽然之前说了fmtLine属性可以混用,但当二者发生重复时,绘制结果以Line属性为标准。

1.2、绘制带标签的数据

如果数据本身带有标签,比如data={'x':x,'y':y},其中x,y为两组大小相同的数组,其标签分别为'x','y',可以通过data['x']data['y']进行访问。如果要对datax、y数据进行绘图,除了可以将data['x']、data['y']作为参数x、y输入外,还可以用如下方法:

plot('x', 'y', data=obj)

即将标签放在对应的x、y处,并添加data参数,这样绘制时,程序会按照data[x标签]、data[y标签]的方式进行绘制。

data的类型可以是dict、pandas.DataFrame

1.3、在一幅图中绘制多个数据集

如何在一幅图像中绘制多个数据集,每个数据集都对应一个折线点集

方法一、最直接的方法——多次调用plot函数

plot(x1, y1, 'bo')
plot(x2, y2, 'go')

方法二、x、y是二维数组

此时有两种情况:

①x、y都是二维数组;

那么它们必须大小相同,假设都是[M,n],那么会绘制n条曲线,每条曲线由M个点构成。第i条曲线的第j个点的坐标为(x[ j ][ i ],y[ j ][ i ])

②x、y其中一个是二维数组;

假设其中一个数据的大小为[M,n],那么另一个数据就必须是一维数组,且长度为M。这样会绘制n条曲线,每个曲线由M个点构成。

假设y是二维数组,x为一维数组,那么第i条曲线第j个点的坐标为(x[ j ],y[ j ][ i ]);

方法三、以参数 [x],y,[fmt]的方式说明每个数据集及绘制方式;

plot(x1, y1, 'g^', x2, y2, 'g-')

在这种情况下,所有额外补充的属性参数将被应用到所有数据集上。这种情况下的data属性将被禁用。

默认情况下,如果我们不特定指出线的属性,那么多条线的属性会按照内置的某种顺序循环出现,具体可见 rcParams["axes.prop_cycle"]

以颜色为例,多条线的颜色按以下顺序循环:

cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])

2、参数

plot(*args, scalex=True, scaley=True, data=None, **kwargs)

2.1、*args

参数

类型

说明

x,y 具体数值或者array-like

具体的横纵坐标,如果省略x,那么x会自动规划为range(len(y))

通常情况下,这两个参数都是1D array;

不过也可以用2D array,具体用法见1.3、方法二所说;

这两个参数在写的时候,直接写变量就行,不能写成x=...,y=...的形式

fmt str 样式字符串,该参数在传入时也是直接写变量,而不是fmt=...
data dict或DataFrame 如果要传入带标签的数据,就需要用到data参数

2.2、其他参数

参数

类型

默认值

说明

scalex、scaley bool True 是否以data的上下限作为坐标轴的显示范围
**kwargs Line2D属性   用于表明线的具体属性(标签、线宽、颜色等)

2.3、**kwargs

该参数用于指明线的具体的属性,这种参数在传入的时候需要写关键字,就像这样plot(...,keyword=...)

这里的Keyword见 Line2D ,罗列如下(有一些属性暂不知道用途,这里列全属性,但是只给出关键属性的用法):

参数

类型

说明

agg_filter

a filter function

 

alpha

scalar or None

透明度

animated

bool

 

antialiased or aa

bool

 

clip_box

Bbox

 

clip_on

bool

 

clip_path

Patch or (Path, Transform) or None

 

color or c

color

颜色

dash_capstyle

CapStyle or {'butt', 'projecting', 'round'}

线的尾迹

dash_joinstyle

JoinStyle or {'miter', 'round', 'bevel'}

连接点的样式

dashes

sequence of floats (on/off ink in points) or (None, None)

 

data

(2, N) array or two 1D arrays

 

drawstyle or ds

{'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default'

点之间的连接线样式

figure

Figure

设置线所属的Figure

fillstyle

{'full', 'left', 'right', 'bottom', 'top', 'none'}

点的填充方式

gid

str

这个图形的id

in_layout

bool

 

label

object

这个图形的标签(用作图例)

linestyle or ls

{'-', '--', '-.', ':', '', (offset, on-off-seq), ...}

线形

linewidth or lw

float

线宽

marker

marker style string, Path or MarkerStyle

标志点的样式,见3.1节marker

markeredgecolor or mec

color

marker的边界颜色

markeredgewidth or mew

float

marker的边线宽度

markerfacecolor or mfc

color

marker的颜色

markerfacecoloralt or mfcalt

color

 

markersize or ms

float

marker的大小

markevery

None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool]

指定绘制marker的间隔,只绘制这些位置处的marker

path_effects

AbstractPathEffect

 

picker

float or callable[[Artist, Event], tuple[bool, dict]]

 

pickradius

float

 

rasterized

bool

 

sketch_params

(scale: float, length: float, randomness: float)

 

snap

bool or None

 

solid_capstyle

CapStyle or {'butt', 'projecting', 'round'}

 

solid_joinstyle

JoinStyle or {'miter', 'round', 'bevel'}

 

transform

unknown

 

url

str

 

visible

bool

是否可见

xdata

1D array

 

ydata

1D array

 

zorder

float

 

3、样式

3.1、marker

All possible markers are defined here:

marker

symbol

description

"."

m00

point

","

m01

pixel

"o"

m02

circle

"v"

m03

triangle_down

"^"

m04

triangle_up

"<"

m05

triangle_left

">"

m06

triangle_right

"1"

m07

tri_down

"2"

m08

tri_up

"3"

m09

tri_left

"4"

m10

tri_right

"8"

m11

octagon

"s"

m12

square

"p"

m13

pentagon

"P"

m23

plus (filled)

"*"

m14

star

"h"

m15

hexagon1

"H"

m16

hexagon2

"+"

m17

plus

"x"

m18

x

"X"

m24

x (filled)

"D"

m19

diamond

"d"

m20

thin_diamond

"|"

m21

vline

"_"

m22

hline

0 (TICKLEFT)

m25

tickleft

1 (TICKRIGHT)

m26

tickright

2 (TICKUP)

m27

tickup

3 (TICKDOWN)

m28

tickdown

4 (CARETLEFT)

m29

caretleft

5 (CARETRIGHT)

m30

caretright

6 (CARETUP)

m31

caretup

7 (CARETDOWN)

m32

caretdown

8 (CARETLEFTBASE)

m33

caretleft (centered at base)

9 (CARETRIGHTBASE)

m34

caretright (centered at base)

10 (CARETUPBASE)

m35

caretup (centered at base)

11 (CARETDOWNBASE)

m36

caretdown (centered at base)

"None"" or ""

 

nothing

'$...$'

m37

Render the string using mathtext. E.g "$f$" for marker showing the letter f.

verts

 

A list of (x, y) pairs used for Path vertices. The center of the marker is located at (0, 0) and the size is normalized, such that the created path is encapsulated inside the unit cell.

3.2、颜色

character

color

'b'

blue

'g'

green

'r'

red

'c'

cyan

'm'

magenta

'y'

yellow

'k'

black

'w'

white

3.3、Linestyle

 

 其中Named Linestyles可以直接通过写线的名字来表示,就像这样:

plot(...,linestyle='solid')

其他的线性则要用Tuple的形式写:

plot(...,linestyle=(0, (1, 10)),...)

 3.4、Text样式

图像中的一个文本是一个Text对象,它的最基本的属性是位置坐标x,y文本字符串text

其他属性罗列如下,只介绍部分常用的:

 

Property

Description

说明

agg_filter

a filter function

 

alpha

scalar or None

透明度

animated

bool

 

backgroundcolor

color

背景色

bbox

dict with properties for patches.FancyBboxPatch

 

clip_box

unknown

 

clip_on

unknown

 

clip_path

unknown

 

color or c

color

文字颜色

figure

Figure

所属画布

fontfamily or family

{FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'}

 

fontproperties or font or font_properties

font_manager.FontProperties or str or pathlib.Path

 

fontsize or size

float or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}

文字大小

fontstretch or stretch

{a numeric value in range 0-1000, 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'}

 

fontstyle or style

{'normal', 'italic', 'oblique'}

文字字体

fontvariant or variant

{'normal', 'small-caps'}

 

fontweight or weight

{a numeric value in range 0-1000, 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'}

样式(黑体、斜体等)

gid

str

 

horizontalalignment or ha

{'center', 'right', 'left'}

 

in_layout

bool

 

label

object

文字标签

linespacing

float (multiple of font size)

 

math_fontfamily

str

 

multialignment or ma

{'left', 'right', 'center'}

 

parse_math

bool

 

path_effects

AbstractPathEffect

 

picker

None or bool or float or callable

 

position

(float, float)

位置

rasterized

bool

 

rotation

float or {'vertical', 'horizontal'}

旋转度数

rotation_mode

{None, 'default', 'anchor'}

 

sketch_params

(scale: float, length: float, randomness: float)

 

snap

bool or None

 

text

object

文本

transform

Transform

 

transform_rotates_text

bool

 

url

str

 

usetex

bool or None

 

verticalalignment or va

{'center', 'top', 'bottom', 'baseline', 'center_baseline'}

 

visible

bool

是否可见

wrap

bool

 

x

float

横坐标

y

float

纵坐标

zorder

float

 
posted @ 2022-05-18 17:01  ShineLe  阅读(1470)  评论(0编辑  收藏  举报