matplotlib基本使用01

matplotlib基本使用01

import numpy as np
import matplotlib.pyplot as plt

import warnings
warnings.filterwarnings("ignore")

matplotlib 采用面向对象的技术来实现,因此组成图表的各个元素都是对象,在编写较大的应用程序的时候,通过面向对象的方式使用matplotlib讲更加有效。但是使用这种面向对象的调用接口进行绘图会比较繁琐,因此matplotlib还提供了进行快速绘图的pyplot模块。同时为了将matplotlib绘制的图表嵌入到Notebook中,需要执行命令:%matplotlib inline

matplotlib-绘制精美的图表

快速绘图

%matplotlib inline
# 使用inline模式在Notebook中绘制的图表会自动进行关闭,为了在Notebook的多个单元格内操作同一幅图表,需要运行下面的魔法命令:
%config InlineBackend.close_figures = False

使用pyplot模块绘图

matplotlib还提供了一个名为pylab的模块,其中包括了许多Numpy和pyplot模块中常用的函数,方便用户快速进行计算和绘图,比较适合在IPython交互式环境中使用。

plt.plot?
#%fig=使用pyplot模块快速将数据绘制成曲线图
import matplotlib.pyplot as plt #❶

x = np.linspace(0, 10, 1000)
# print("x的值:{}".format(x))
y = np.sin(x)
# print("y的值:{}".format(y))
z = np.cos(x**2)
# print("z的值:{}".format(z))

plt.figure(figsize=(8,4)) #❷ 调用figure()创建一个Figure(图表)对象,并且将它称为当前Figure对象。也可以不创建,直接条用plot()来进行绘图。

plt.plot(x,y,label="$sin(x)$",color="red",linewidth=2) #❸  label该曲线指定一个标签,用于在图中显示。如果标签字符串的前后有字符"$",显示为Latex
plt.plot(x,z,"b--",label="$cos(x^2)$") #❹  通过"b--"指定曲线的颜色和线型,b--蓝色,--代表虚线。

plt.xlabel("Time(s)") #❺ 分别设置x,y轴的标题文字
plt.ylabel("Volt") 
plt.title("PyPlot First Example")  # 设置子图的标题
plt.ylim(-1.2,1.2)  # 分别设置x,y轴的显示范围
plt.legend()  # 显示图示,即图中表示每条曲线的标签(label)和样式的矩形区域。

plt.show() #❻ 调用plt.show()显示绘图窗口

plt.savefig("./t1.png", dpi = 120) # 将当前的Figure对象保存为图像文件,图像格式由文件的拓展名决定。

在这里插入图片描述

WARNING

使用LaTeX语法绘制数学公式会极大地降低图表的描绘速度。

plt.savefig("test.png", dpi=120)
<Figure size 432x288 with 0 Axes>

TIP

如果关闭了图表窗口,则无法使用savefig()保存图像。实际上不需要调用show()显示图表,可以直接用savefig()将图表保存成图像文件。使用这种方法可以很容易编写批量输出图表的程序。

为了更好的实现保存,要执行:%config InlineBackend.close_figures = False

import io
buf = io.BytesIO() # 创建一个用来保存图像内容的BytesIO对象
plt.savefig(buf, fmt="png") # 将图像以png格式保存进buf中
buf.getvalue()[:20] # 显示图像内容的前20个字节
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x02@'

面向对象方式绘图

pyplot模块的内部保存了当前图表以及当前子图等信息。可以使用gcf()和gca()获得这两个对象,“get current figure”“get current axes”

fig = plt.gcf()
axes = plt.gca()
print( fig, axes)
Figure(576x288) AxesSubplot(0.125,0.125;0.775x0.755)

配置属性

#%fig[1x3]=配置绘图对象的属性
plt.figure(figsize=(4, 3))
x = np.arange(0, 5, 0.1)
print('x的值:{}'.format(x))
line = plt.plot(x, 0.05*x*x, "bo")[0] # plot返回一个列表
line.set_alpha(0.5) # 调用Line2D对象的set_*()方法设置属性值,修改他在图表中对应曲线的透明度
x的值:[0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.  1.1 1.2 1.3 1.4 1.5 1.6 1.7
 1.8 1.9 2.  2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 3.  3.1 3.2 3.3 3.4 3.5
 3.6 3.7 3.8 3.9 4.  4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9]

在这里插入图片描述

lines = plt.plot(x, np.sin(x), x, np.cos(x))
plt.setp(lines, color="r", linewidth=4.0) # 调用step()可以同时配置多个对象的属性,这里同时设置两条曲线的颜色和线宽
[None, None, None, None]
print( line.get_linewidth())
print( plt.getp(lines[0], "color")) # 返回color属性
1.5
r
# getp和setp不同,他只能对一个对象进行操作,可以指定属性名或者不指定属性名。
f = plt.gcf()
plt.getp(f)
    agg_filter = None
    alpha = None
    animated = False
    axes = [<matplotlib.axes._subplots.AxesSubplot object at ...
    children = [<matplotlib.patches.Rectangle object at 0x0000024...
    clip_box = None
    clip_on = True
    clip_path = None
    constrained_layout = False
    constrained_layout_pads = (0.04167, 0.04167, 0.02, 0.02)
    contains = None
    default_bbox_extra_artists = [<matplotlib.axes._subplots.AxesSubplot object at ...
    dpi = 72.0
    edgecolor = (1.0, 1.0, 1.0, 0.0)
    facecolor = (1.0, 1.0, 1.0, 0.0)
    figheight = 3.0
    figure = None
    figwidth = 4.0
    frameon = True
    gid = None
    in_layout = True
    label = 
    path_effects = []
    picker = None
    rasterized = None
    size_inches = [4. 3.]
    sketch_params = None
    snap = None
    tight_layout = False
    transform = IdentityTransform()
    transformed_clip_path_and_affine = (None, None)
    url = None
    visible = True
    window_extent = TransformedBbox(     Bbox(x0=0.0, y0=0.0, x1=4.0, ...
    zorder = 0
print( plt.getp(f, "axes"), plt.getp(f, "axes")[0] is plt.gca())
[<matplotlib.axes._subplots.AxesSubplot object at 0x0000024C0FFD9588>] True
alllines = plt.getp(plt.gca(), "lines")
print( alllines, alllines[0] is line) # 其中的第一条曲线就是最开始绘制的那条曲线
<a list of 3 Line2D objects> True
print( f.axes, len(f.axes[0].lines))
[<matplotlib.axes._subplots.AxesSubplot object at 0x0000024C0FFD9588>] 3

绘制多子图

可以使用subplot()快速绘制包含多个子图的图表,调用形式为:subplot(numRows, numcols,plotNum).如果,numRows,numcols和plotNum三个参数都是小于10的,则可以把他们缩写为一个整数,例如:subplot(322)和subplot(3, 2, 3)的含义相同。

#%fig[1x2]=在Figure对象中创建多个子图
for idx, color in enumerate("rgbyck"):   # 三行两列共六个子图,并通过axisbg参数给每个子图设置不同的背景颜色。
    plt.subplot(321+idx, axisbg=color)
# 如果希望某个子图占据整行或者整列,可以如下调用subplot()
plt.subplot(221) # 第一行的左图
plt.subplot(222) # 第一行的右图
plt.subplot(212) # 第二整行;
plt.show()

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

#%hide
plt.close("all")
#%fig[1x2]=同时在多幅图表、多个子图中进行绘图
plt.figure(1) # 创建图表1
plt.figure(2) # 创建图表2
ax1 = plt.subplot(121) # 在图表2中创建子图1
ax2 = plt.subplot(122) # 在图表2中创建子图2

x = np.linspace(0, 3, 100)
for i in range(5):
    plt.figure(1)  #❶ 选择图表1
    plt.plot(x, np.exp(i*x/3))
    plt.sca(ax1)   #❷ 选择图表2的子图1
    plt.plot(x, np.sin(i*x))
    plt.sca(ax2)  # 选择图表2的子图2
    plt.plot(x, np.cos(i*x))
plt.show()

在这里插入图片描述

在这里插入图片描述

TIP

也可以不调用sca()指定当前子图,而直接调用ax1ax2plot()方法绘图。

"""
这里的axes是一个形状为:(2,3)的数组,每个元素都是一个子图对象,可以利用Python的赋值语句功能将这个数组中的每个元素用一个变量来表示.
"""
#%nofig
fig, axes = plt.subplots(2, 3)
[a, b, c], [d, e, f] = axes
print( axes.shape)
print(b)
AxesSubplot(0.125,0.536818;0.227941x0.343182)

在这里插入图片描述

"""还可使用subplot2grid()进行更加复杂的表格布局。表格布局和Excel或者word中绘制表格十分类似"""
'还可使用subplot2grid()进行更加复杂的表格布局。表格布局和Excel或者word中绘制表格十分类似'

调用形式:subplot2grid(shape, loc, rowspan=1, colspan=1, **kwargs) 。其中,shape为表示表格形状的元组(行数,列数)。loc为子图左上角所在的座标:(行,列)。rowspan和colspan分别为子图所占据的行数和列数。下面是在3X3的网格上创建5个子图。在每个子图中,显示该子图对应的变量名。

#%fig=使用subplot2grid()创建表格布局
fig = plt.figure(figsize=(6, 6))
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=2)
ax2 = plt.subplot2grid((3, 3), (0, 2), rowspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 0), rowspan=2)
ax4 = plt.subplot2grid((3, 3), (2, 1), colspan=2)
ax5 = plt.subplot2grid((3, 3), (1, 1));
#%hide
for idx, ax in enumerate(fig.axes, 1):
    ax.text(0.5, 0.5, "ax{}".format(idx), ha="center", va="center", fontsize=16)

在这里插入图片描述

配置文件

前面的绘图过程中,没有逐一对图表的属性进行配置,而是直接采用matplotlib的默认配置。matplotlib将这些默认配置保存在一个名字为matplotlibrc的配置文件中,通过修改配置文件,可以修改图表的默认样式。

from os import path
path.abspath(matplotlib.get_configdir())
u'C:\\Users\\RY\\Dropbox\\scipybook2\\settings\\.matplotlib'
path.abspath(matplotlib.matplotlib_fname())
u'C:\\Users\\RY\\Dropbox\\scipybook2\\settings\\.matplotlib\\matplotlibrc'
print(matplotlib.rc_params())
agg.path.chunksize: 0
animation.avconv_args: []
animation.avconv_path: avconv
animation.bitrate: -1
...
print(matplotlib.rcParams)
agg.path.chunksize: 0
animation.avconv_args: []
animation.avconv_path: avconv
animation.bitrate: -1
...
#%hide
plt.close("all")
%%disabled
matplotlib.rcParams["lines.marker"] = "o"
plt.plot([1,2,3,2])
%%disabled
matplotlib.rc("lines", marker="x", linewidth=2, color="red")
%%disabled
matplotlib.rcdefaults()
%%disabled
matplotlib.rcParams.update( matplotlib.rc_params() )

TIP

通过pyplot模块也可以使用rcParamsrcrcdefaults

matplotlib.style模块提供绘图样式切换功能,所有可选样式可以通过available获得。

from matplotlib import style
print( style.available)
['bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark-palette', 'seaborn-dark', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'seaborn', 'Solarize_Light2', 'tableau-colorblind10', '_classic_test']
# 调用use()函数可以切换样式,下面使用ggplot样式绘图。
style.use("ggplot")
#%figonly=使用ggplot样式绘图
import numpy as np
import matplotlib.pyplot as plt

style.use("ggplot")

plt.close("all")

x = np.linspace(0, 10, 1000)
y = np.sin(x)
z = np.cos(x**2)

plt.figure(figsize=(8,4))

plt.plot(x,y,label="$sin(x)$",linewidth=2)
plt.plot(x,z,"--",label="$cos(x^2)$")

plt.xlabel("Time(s)")
plt.ylabel("Volt") 
plt.title("ggplot style") 
plt.ylim(-1.2,1.2) 
plt.legend() # 显示图示,在图中表示每条曲线的标签(label)和样式的矩形区域。
<matplotlib.legend.Legend at 0x24c11950a08>

在这里插入图片描述

在图表中显示中文

from matplotlib.font_manager import fontManager
fontManager.ttflist[:6]
[<Font 'cmsy10' (cmsy10.ttf) normal normal 400 normal>,
 <Font 'cmss10' (cmss10.ttf) normal normal 400 normal>,
 <Font 'cmb10' (cmb10.ttf) normal normal 400 normal>,
 <Font 'DejaVu Serif' (DejaVuSerif-BoldItalic.ttf) italic normal bold normal>,
 <Font 'cmtt10' (cmtt10.ttf) normal normal 400 normal>,
 <Font 'DejaVu Serif' (DejaVuSerif-Italic.ttf) italic normal 400 normal>]

ttflist是matplotlib的系统字体列表。其中每个元素是表示字体的Font对象,如下:显示第一个字体的全路径和字体名。

print (fontManager.ttflist[0].name)
print (fontManager.ttflist[0].fname)
cmsy10
D:\installation\anaconda3\lib\site-packages\matplotlib\mpl-data\fonts\ttf\cmsy10.ttf
#%hide
plt.close("all")
scpy2/matplotlib/chinese_fonts.py

SOURCE

scpy2/matplotlib/chinese_fonts.py:显示系统中所有文件大于1M的TTF字体,请读者使用该程序查询计算机中可使用的中文字体名。

#%fig=显示系统中所有的中文字体名
import os
from os import path

fig = plt.figure(figsize=(8, 7))
ax = fig.add_subplot(111)
plt.subplots_adjust(0, 0, 1, 1, 0, 0)
plt.xticks([])
plt.yticks([])
x, y = 0.05, 0.05
fonts = [font.name for font in fontManager.ttflist if 
             path.exists(font.fname) and os.stat(font.fname).st_size>1e6] #❶
font = set(fonts)
dy = (1.0 - y) / (len(fonts) // 4 + (len(fonts)%4 != 0))

for font in fonts:
    t = ax.text(x, y + dy / 2, u"中文字体", 
                {'fontname':font, 'fontsize':14}, transform=ax.transAxes) #❷
    ax.text(x, y, font, {'fontsize':12}, transform=ax.transAxes)
    x += 0.25
    if x >= 1.0:
        y += dy
        x = 0.05
plt.show()

在这里插入图片描述

#%nofig
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14) #❶
t = np.linspace(0, 10, 1000)
y = np.sin(t)
plt.close("all")
plt.plot(t, y)
plt.xlabel(u"时间", fontproperties=font) #❷
plt.ylabel(u"振幅", fontproperties=font)
plt.title(u"正弦波", fontproperties=font)
plt.show()

在这里插入图片描述

为了缩短启动时间,matplotlib不会在每次启动时都重新扫描所有的字体文件并创建字体列表,因此在复制完字体文件之后,需要运行下面的语句重新创建字体列表。

from matplotlib.font_manager import _rebuild
_rebuild()

也可以直接修改配置字典,设置默认的字体。这样就不需要在每次绘制文字时设置字体

%%disabled
plt.rcParams["font.family"] = "SimHei"
plt.plot([1,2,3])
plt.xlabel(0.5 ,0.5, u"中文字体")
#%hide
%exec_python -m scpy2.matplotlib.chinese_fonts
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章