Matplotlib

简介

每次使用到,都要网上查一下相关的例子,所以在这里摘录一些做一下总结。

Matplotlib 是一个用于在 Python 中绘制数组的 2D 图形库。虽然它起源于模仿 MATLAB图形命令,但它独立于 MATLAB,可以以 Pythonic 和面向对象的方式使用。虽然 Matplotlib 主要是在纯 Python 中编写的,但它大量使用 NumPy 和其他扩展代码,即使对于大型数组也能提供良好的性能。

pyplot

plt.plot()

matplotlib.pyplot是一个命令风格函数的集合,使matplotlib的机制更像 MATLAB。

#最简单的使用
import matplotlib.pyplot as plt
plt.plot([0,1,2,3,4])
plt.ylabel('demo')
plt.show()

此时,只有一个数组,所以matplotlib认定其是y值序列,并自动生成一个x序列,默认从0开始。
相对的,也可以指定x,y两个数组。

plt.plot([0,1,2,3,4],[0,1,2,3,4])

对于每个x,y参数对,有一个可选的第三个参数,它是指示图形颜色和线条类型的格式字符串。 格式字符串的字母和符号来自 MATLAB,并且将颜色字符串与线型字符串连接在一起。 默认格式字符串为"b-",它是一条蓝色实线。
有关线型和格式字符串的完整列表:

符号描述
‘-’实线
‘–’长虚线
‘-.’点划线
‘:’点线
‘.’点标记
‘v’倒三角标记
‘^’正三角标记
‘<’左三角标记
‘>’右三角标记
‘s’矩形标记

更多见文档pyplot文档

plt.axis()参数为一个列表[xmin,xmax,ymin,ymax],指定轴域的可视区域。

plt.plot([0,1,2,3,4],[0,1,2,3,4],'b-')
plt.axis([0,5,0,5])

此外,为丰富数据处理,常与numpy一起使用,将列表转化为numpy数组。

控制线条属性

线条有许多你可以设置的属性,设置方法如下

  1. 使用关键字参数:
plt.plot(x, y, linewidth=2.0)
  1. setp()命令
lines = plt.plot(x1, y1, x2, y2)
# 使用关键字参数
plt.setp(lines, color='r', linewidth=2.0)
# 或者 MATLAB 风格的字符串值对
plt.setp(lines, 'color', 'r', 'linewidth', 2.0)
属性值类型
alpha浮点值
animated[True / False]
antialiased or aa[True / False]
clip_boxmatplotlib.transform.Bbox 实例
clip_on[True / False]
clip_pathPath 实例, Transform,以及Patch实例
color or c任何 matplotlib 颜色
contains命中测试函数
dash_capstyle[‘butt’ / ‘round’ / ‘projecting’]
dash_joinstyle[‘miter’ / ‘round’ / ‘bevel’]
dashes以点为单位的连接/断开墨水序列
data(np.array xdata, np.array ydata)
figurematplotlib.figure.Figure 实例
label任何字符串
linestyle or ls[ ‘-’ / ‘–’ / ‘-.’ / ‘:’ / ‘steps’ / …]
linewidth or lw以点为单位的浮点值
lod[True / False]
marker[ ‘+’ / ‘,’ / ‘.’ / ‘1’ / ‘2’ / ‘3’ / ‘4’ ]
markeredgecolor or mec任何 matplotlib 颜色
markeredgewidth or mew以点为单位的浮点值
markerfacecolor or mfc任何 matplotlib 颜色
markersize or ms浮点值
markevery[ None / 整数值 / (startind, stride) ]
picker用于交互式线条选择
pickradius线条的拾取选择半径
solid_capstyle[‘butt’ / ‘round’ / ‘projecting’]
solid_joinstyle[‘miter’ / ‘round’ / ‘bevel’]
transformmatplotlib.transforms.Transform 实例
visible[True / False]
xdatanp.array
ydatanp.array
zorder任何数值

多个图形或轴域

这里的figure()命令是可选的,因为默认情况下将创建figure(1),如果不手动指定任何轴域,则默认创建subplot(111)。subplot()命令指定numrows,numcols,fignum,其中fignum的范围是从1到numrows * numcols。 如果numrows * numcols <10,则subplot命令中的逗号是可选的。 因此,子图subplot(211)与subplot(2, 1, 1)相同。 你可以创建任意数量的子图和轴域。

import matplotlib.pyplot as plt
plt.figure(1)                # 第一个图形
plt.subplot(211)             # 第一个图形的第一个子图
plt.plot([1, 2, 3])
plt.subplot(212)             # 第一个图形的第二个子图
plt.plot([4, 5, 6])

plt.figure(2)                # 第二个图形
plt.plot([4, 5, 6])          # 默认创建 subplot(111)

plt.figure(1)                # 当前是图形 1,subplot(212)
plt.subplot(211)             # 将第一个图形的 subplot(211) 设为当前子图
plt.title('1, 2, 3') # 子图 211 的标题
plt.show()

figure1
figure2此外,函数subplots_adjust支持对figure的一些边界空白进行修改,默认为(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)

left = 0.125    # the left side of the subplots of the figure
right = 0.9     # the right side of the subplots of the figure
bottom = 0.1   # the bottom of the subplots of the figure
top = 0.9     # the top of the subplots of the figure
wspace = 0.2   # the amount of width reserved for space between subplots,
         # expressed as a fraction of the average axis width
hspace = 0.2   # the amount of height reserved for space between subplots,
        # expressed as a fraction of the average axis height

fig = plt.figure()
#为figure设置标题
fig.suptitle('TEST', fontsize=14, fontweight='bold')#大小14,加粗

ax = fig.add_subplot(121)
fig.subplots_adjust(top=0.85, wspace = 0.25 )
ax.set_title('axes1 title')
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')
ax.plot([1,2,3,4])

#子图加标题
ax2 = fig.add_subplot(122)
ax2.set_title('axes2 title')
ax2.plot([1,2,1,4])
#坐标轴加标签
ax2.set_xlabel('xlabel')
ax2.set_ylabel('ylabel')

plt.show()

运行效果图

处理文本

text()----在任意位置添加文本;
xlabel()----将标签添加到x轴;
ylabel()----将标签添加到y轴;
title()----将标题添加到Axes;
figtext()-在任意位置添加文本Figure;
suptitle()-添加标题到Figure;
annotate() - 添加注释,用可选箭头,向Axes。

import matplotlib.pyplot as plt

fig = plt.figure()
#为figure设置标题
fig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold')#大小14,加粗

ax = fig.add_subplot(111)
fig.subplots_adjust(top=0.85)
#子图加标题
ax.set_title('axes title')

#坐标轴加标签
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')

#3,8位置加标签,斜体,背景色红色,透明度0.5,
ax.text(3, 8, 'boxed italics text in data coords', style='italic',
        bbox={'facecolor':'red', 'alpha':0.5, 'pad':10})

#公示支持latex 
ax.text(2, 6, r'an equation: $E=mc^2$', fontsize=15)

ax.text(3, 2, u'unicode: Institut f\374r Festk\366rperphysik')

ax.text(0.95, 0.01, 'colored text in axes coords',
        verticalalignment='bottom', horizontalalignment='right',
        transform=ax.transAxes,
        color='green', fontsize=15)

#划线做标签
ax.plot([2], [1], 'o')
ax.annotate('annotate', xy=(2, 1), xytext=(3, 4),
            arrowprops=dict(facecolor='black', shrink=0.05))

ax.axis([0, 10, 0, 10])

plt.show()

结果

参考链接

  1. https://liam.page/2014/09/11/matplotlib-tutorial-zh-cn/
  2. https://wizardforcel.gitbooks.io/matplotlib-user-guide/3.1.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值