python3 matplotlib_python3画图——matplotlib

简介

在matplotlib中,一切看见元素都是Artist,所有对象都是Artist的子类。Artist对象可分位两类:容器类型和简单类型

容器类型:可以包含其他Artist对象的对象。如Figure, Axes等

简单类型:标准的,最基本的绘图原件,不能再包含其他对象。如Line2D, Text, Rectangle等

关于画图,从操作步骤看,可以简化为以下几步:建立figure

建立ax

画图(可使用ax,或者matplotlib.pyplot)

修饰设计

保存

建立figure

讲解

创建一个Figure就是在画布上定义一块矩形区域,它有两个用处:再划分多个子区域

提供坐标系统,左下角为[0,0]点,右上角为[1,1]点

函数

matplotlib.figure.Figure(figsize=None, dpi=None, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, subplotpars=None, tight_layout=None, constrained_layout=None)

参数说明:figsize: 画布大小,默认:rcParam['figure.figsize'] (默认:[6.4, 4.8])

dpi: 像素,默认:100

facecolor:默认白色,边框旁白背景颜色

edgecolord:默认白色,边框线条颜色

linewidth:边框线条粗细

frameon: 是否有边框,默认为True

subplotpars:定义子图参数,是figure.SubplotParams的子类。默认figure.SubplotParams(lelf=None, bottom=None, right=None, top=None, wspace=None, hspace=None)

tight_layout:布尔值,axs离figure的旁白部分,如果False,则默认subplotpars参数。如果为True,则旁白宽度是字体的1.08倍

代码

from matplotlib.figure import Figure

fig = Figure()

import matplotlib.pyplot as plt

fig = plt.figure()

方法

添加物理位置子图:add_axes(rect, projection=None, polar=False, **kwargs)rect: [left, bottom, width, height]

rect = l, b, w, h

fig = plt.figure()

ax = fig.add_axes(rect, projection='polar')

fig.delaxes(ax)

添加子图布局:add_gridspec(nrows, ncols, *kwargs)nrows: 子图行数

ncols:子图列数

结合subplots使用

fig = plt.figure()

gs = fig.add_gridspec(2, 2)

ax1 = fig.add_subplot(gs[0, 0])

ax2 = fig.add_subplot(gs[1, 0], sharex = ax1)

# spans two rows:

ax3 = fig.add_subplot(gs[:, 1])

添加相对位置子图:add_subplot(*args, **kwargs)*frameon:坐标轴显示与否,默认True

sharex,sharey:共享某个坐标轴的x轴或者y轴,它的值是axe

对齐坐标轴标签(不是坐标轴是标签):align_xlabels(self, axs=None)

设置画布标题:text(self, x, y, s, fontdict=None, withdash=, **kwargs)x,y:画布中所处位置

s:标题文字

fontdict:字体

建立Axes

matplotlib.axes.Axes(fig, rect, facecolor=None, frameon=True, sharex=None, sharey=None, label='', xscale=None, yscale=None, **kwargs)fig:画布名称

rect:[left, bottom, width, height]位置

sharex/sharey:共享坐标轴的axes

frameon: 是否可视化轴线,默认True

xlabel/ylabel:坐标轴标签

xlim/ylim:坐标轴范围

title:坐标轴名称

xscale/yscale: 坐标轴刻度尺度,{"linear", "log", "symlog", "logit", ...}

xticks:坐标轴刻度

xticklabels: List[str] ,坐标轴标签

*** 以上属性可使用 ax.set_属性名()来设置

*** 以上属性可通过 ax.get_属性名()来获取

方法

画图

Axes.plot(x, y1, y2=0, where=None,)

Axes.fill_between(self, x, y1, y2=0, where=None, interpolate=False, step=None, *, data=None, **kwargs)

fig, ax = plt.subplots()

ax.plot(x, y1, x, y2, color='black')

ax.fill_between(x, y1, y2, where=y2 >y1, facecolor='yellow', alpha=0.5)

ax.fill_between(x, y1, y2, where=y2 <=y1, facecolor='red', alpha=0.5)

ax.set_title('Fill Between')

Axes.fill_betweenx(self, y, x1, x2=0, where=None, step=None, interpolate=False, *, data=None, **kwargs)

Axes.bar

Axes.barh

Axes.stem([x, ], y, linefmt=None, markerfmt=None, basefmt=None)linefmt:线型

markerfmt:标记形状

bottom:y轴基准线

Axes.eventplot(positions,, orientation='horizontal', lineoffsets=1, linelengths=1, linewidths=None, colors=None, linestyles='solid', *, data=None, **kwargs)position:一维或者二维数组,事件位置

orientation:方向

lineoffsets:不同类型事件之间的距离

Axes.pie(self, x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None, radius=None, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False, rotatelabels=False, *, data=None)

Axes.stackplot(x,y,*args, labels=(), colors=None, baseline='zero', data=None, **kwargs)

Axes.broken_barh(self, xranges, yrange, *, data=None, **kwargs) 分块矩阵画图xranges:sequence of tuples (xmin, xwidth)

yrange:(ymin, yheight)

data:数据源,使用数据源,xranges,yrange使用data的键即可

Axes.vlines(self, x, ymin, ymax, colors='k', linestyles='solid', label='', *, data=None, **kwargs)

Axes.axvline(self,x) # 只画一条竖线

Axes.hlines(self, x, ymin, ymax, colors='k', linestyles='solid', label='', *, data=None, **kwargs)

Axes.axhline(self, y) # 只画一条水平线

Axes.fill(x,y,data=None,**kwargs) # x,y确定多边形的顶点,涂描多边形

ax.fill("time", "signal",data={"time": [0, 1, 2], "signal": [0, 1, 0]})

标签

annotate(self, s, xy, *args, **kwargs)text: 内容

xy:(float, float)要注释的点

xytext:(float, float)注释文本的位置,如果没有,则默认为xy

xycoords:坐标系,可选参数'figure points' | 'figure pixels' | 'figure fraction' | 'axes points'... | 'data'

arrowprops: dict,箭头属性,key建议直接考虑'arrowstyle',可选值有 ’-‘ | ’->' | '

text(self, x, y, s, fontdict=None, withdash=, **kwargs)x,y: 文本位置

s:文本内容

horizontalalignment:水平相对位置,如’center' | 'left' ...

verticalalignment:竖直相对位置

arrow(self, x, y, dx, dy, **kwargs) # 添加箭头

inset_axes(self, bounds, *, transform=None, zorder=5, **kwargs) # 添加子图bounds:[x0, y0, width, height], 子图的范围

transform:子图的刻画单位,默认为[0,1], 也可选ax.transData,按照数据来

secondary_xaxis(self, location, *, functions=None, **kwargs)

secondary_yaxis(self, location, *, functions=None, **kwargs)

显示

Axes.set_axis_off / Axes.set_axis_on

Axes.grid(self, b=None, which='major', axis='both', **kwargs)b:bool,是否显示网格,默认为True

which:{‘major', 'minor', 'both'}, 在什么级别坐标tick上显示网格线

axis: {'both', 'x', 'y'}

获取/设置数据

set/get:xlim, xlabel, title, legend

Axes.legend(*args, **kwargs)handels:图句柄

babels:句柄标签

loc:位置,选项有 ’best‘(0) | 'upper right'(1) | 'upper left'(2) | 'lower left'(3) | 'lower right'(4) | 'right'(5) | 'center left'(6) | 'center right'(7) | 'lower center'(8) | 'upper center'(9) | 'center'(10)

bbox_to_anchor:loc绝对位置(x, y, width, height),例如(0.5, 0., 0.5, 0.5), (0.5, 0.5)

ncol:标签的列数,默认为1

frameon:是否有边框

fontsize:字体大小

坐标轴刻度

set/get: xticks, xticklabels

Axes.minorticks_off/ Axes.minorticks_on: 移除/增加小刻度

Axes.tick_params(self, axis='both', **kwargs)axis: {'both', 'x', 'y'}

which: {'major', 'minor', 'both'}

direction:刻度位置, ’in' | 'out' | 'input'

pad:tick和label之间的距离

labelcolor,colors

bottom, top, left, right:bool值,刻度位置

labelbottom, labeltop, labelleft, labelright: bool值,刻度标签位置

labelrotation:倾斜度

增加部件

add_: artist, child_axes, collection, container, image, line, patch, table

Axes.twinx/ Axes.twiny

建立坐标轴和刻度

class `matplotlib.axis.XAxis(axes, pickradius=15)

class `matplotlib.axis.YAxis(axes, pickradius=15)

设置format案例

from matplotlib.ticker import FuncFormatter

import matplotlib.pyplot as plt

def ac(tick: '刻度', pos:'位置'):

return ['a','b','c','d'][tick]

fig = plt.figure()

ax = fig.add_subplot(111)

plt.plot([0,1,2],[7,8,9])

ax.set_xticks([1,2,3])

ax.xaxis.set_major_formatter(FuncFormatter(ac))

保存图片savefig(fname,*, transparent=None, **kwargs)

fname:图片名称

dpi:保存的像素,如果为None,则默认rcParams['savefig.dpi'].如果是’figure‘,则使用图片像素

facecolor:背景颜色

edgecolor:边框颜色

format:图片格式,如’png‘,’pdf‘,’svg'

bbox_inches:如果是‘tight’,则会剪裁图周围的空白

pad_inches:当bbox_inches为‘tight’时候剩余的幅度。只在tight情况下有用

plt.savefig('sdf2.png',bbox_inches='tight',pad_inches=0)

更新:工作中的一段代码案例

fig = plt.figure(figsize=[12.8*2,3.6*3])

ax_311 = fig.add_subplot(311)

ax_311.set_title(f'{kbarPeriod}周期kbar上1天波动率差值行情走势图',fontsize=16)

x_tick = range(data_len)

plt.plot(x_tick, closeM)

ax_312 = fig.add_subplot(312, sharex = ax_311)

plt.plot(x_tick, vol_1day_kbarP)

plt.ylim([0, 5])

ax_313 = fig.add_subplot(313, sharex = ax_311)

plt.plot(x_tick, volDiff_1day_kbarP)

plt.subplots_adjust(wspace =0, hspace =0)

x_shijian = kbarData['timestamp'].dt.strftime('%Y%m%D %H:%M')

step = int(data_len // 10)

x_tick_show = range(0, data_len, step)

x_tick_label = x_shijian.iloc[x_tick_show]

plt.xticks(x_tick_show, x_tick_label, rotation=-30)

path_png_bin_i = path_png_bin.joinpath(f'{kbarPeriod}周期kbar上1天波动率差值行情走势图.png')

plt.savefig(path_png_bin_i, bbox_inches='tight',pad_inches=0)

worksheet.insert_image(row, col, path_png_bin_i)

bin_data = hist_z(volDiff_1day_kbarP, bins)

worksheet.write_column(row+1, col+31, bins)

worksheet.write_column(row+1, col+31+1, bin_data)

worksheet.write_column(row+1, col+31+2, bin_data/np.sum(bin_data))

decribe_data = volDiff_1day_kbarP.describe()

worksheet.write_column(row+1, col+31+4, list(decribe_data.index))

worksheet.write_column(row+1, col+31+5, list(decribe_data))

row += row_add

workbook.close()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值