【Python】【matplotlib】面向对象方式绘图
来源:互联网 发布:辐射4女角色捏脸数据 编辑:程序博客网 时间:2024/06/04 19:32
不用面向对象方式画图,优点在于代码简单,缺点在于画多图和多子图附带各种标注时,代码很乱。
当然,更复杂和标注清晰的图,大部分需求场景是成熟的可视化展示,这种情况下用echart更好。
各个对象
plt.figure()
先生成一个figure,在figure上生成一个Axes,在Axes上面生成line(plot),或者生成patch(bar&hist)
它们之间的关系参照这段代码:
f.axes[0].lines[0]
获取的方法1
f=plt.gcf()#get current figurea=plt.gca()#get current axes
获取的方法2
f=plt.gcf()a=plt.getp(f,'axes')[0]l=plt.getp(f,'lines')[0]
共有属性
这些对象共有的一些属性:
figure
f=plt.gcf()f=plt.figure(1)
figure的类型是:
<class 'matplotlib.figure.Figure'>
figure下的属性(用plt.getp(f)获取)
agg_filter = Nonealpha = Noneanimated = Falseaxes = [<matplotlib.axes._subplots.AxesSubplot>]children = [<matplotlib.patches.Rectangle>]clip_box = Noneclip_on = Trueclip_path = Nonecontains = Nonedefault_bbox_extra_artists = [<matplotlib.axes._subplots.AxesSubplot>]dpi = 72.0edgecolor = (1.0, 1.0, 1.0, 0.0)facecolor = (1.0, 1.0, 1.0, 0.0)figheight = 4.0figure = Nonefigwidth = 6.0frameon = Truegid = Nonelabel =path_effects = []picker = Nonerasterized = Nonesize_inches = [ 6. 4.]sketch_params = Nonesnap = Nonetight_layout = Falsetransform = IdentityTransform()transformed_clip_path_and_affine = (None, None)url = Nonevisible = Truewindow_extent = TransformedBbox(Bbox([[0.0, 0.0], [6.0, 4.0]]))zorder = 0
一些解释:
Axes
对象信息:
<matplotlib.axes._subplots.AxesSubplot at 0x263c9ba9320>
可以有两种方法获取
a1=plt.getp(f,'axes')#生成的是一个lista2=plt.gca()#当前激活的axes
axes对象的属性:(用plt.getp(a2)获取)
adjustable = boxagg_filter = Nonealpha = Noneanchor = Canimated = Falseaspect = autoautoscale_on = Falseautoscalex_on = Trueautoscaley_on = Falseaxes = Axes(0.125,0.125;0.775x0.755)axes_locator = Noneaxis_bgcolor = (1.0, 1.0, 1.0, 1)axisbelow = linechildren = [<matplotlib.lines.Line2D>]clip_box = Noneclip_on = Trueclip_path = Nonecontains = Nonecursor_props = (1, (0.0, 0.0, 0.0, 1))data_ratio = 0.36363636363636365default_bbox_extra_artists = [<matplotlib.lines.Line2D>]facecolor = (1.0, 1.0, 1.0, 1)fc = (1.0, 1.0, 1.0, 1)figure = Figure(432x288)frame_on = Truegeometry = (1, 1, 1)gid = Noneimages = <a list of 0 AxesImage objects>label =legend = Nonelegend_handles_labels = ([], [])lines = <a list of 34 Line2D objects>navigate = Truenavigate_mode = Nonepath_effects = []picker = Noneposition = Bbox(x0=0.125, y0=0.125, x1=0.9, y1=0.88)rasterization_zorder = Nonerasterized = Nonerenderer_cache = Noneshared_x_axes = <matplotlib.cbook.Groupershared_y_axes = <matplotlib.cbook.Groupersketch_params = Nonesnap = Nonesubplotspec = <matplotlib.gridspec.SubplotSpectitle = Pyplottransform = IdentityTransform()transformed_clip_path_and_affine = (None, None)url = Nonevisible = Truewindow_extent = Bbox(x0=50.5, y0=32.5, x1=392.3, y1=256.94)xaxis = XAxis(54.000000,36.000000)xaxis_transform = BlendedGenericTransform(CompositeGenericTransform(...))xbound = (-0.30000000000000004, 6.2999999999999998)xgridlines = <a list of 9 Line2D xgridline objects>xlabel = Time(s)xlim = (-0.30000000000000004, 6.2999999999999998)xmajorticklabels = <a list of 9 Text xticklabel objects>xminorticklabels = <a list of 0 Text xticklabel objects>xscale = linearxticklabels = <a list of 9 Text xticklabel objects>xticklines = <a list of 18 Text xtickline objects>xticks = [-1. 0. 1. 2. 3. 4.]...yaxis = YAxis(54.000000,36.000000)yaxis_transform = BlendedGenericTransform(BboxTransformTo(Transforme...))ybound = (-1.2, 1.2)ygridlines = <a list of 7 Line2D ygridline objects>ylabel = Voltylim = (-1.2, 1.2)ymajorticklabels = <a list of 7 Text yticklabel objects>yminorticklabels = <a list of 0 Text yticklabel objects>yscale = linearyticklabels = <a list of 7 Text yticklabel objects>yticklines = <a list of 14 Line2D ytickline objects>yticks = [-1.5 -1. -0.5 0. 0.5 1. ]...zorder = 0
Axes的方法
显示legend:ax1.legend()
自动调整横纵坐标:ax.autoscale_view()
不显示坐标轴:ax.set_axis_off()
axes对象可以包含的对象
line
对象信息:
<matplotlib.lines.Line2D at 0x263c9fc0a20>
获取方法类似
l=plt.getp(a,'lines')#是一个listl=plt.plot(...)#这个可以注意一下l=plt.plot(x,y,label="$sin(x)$",color='red',linewidth=2)#可以直接在plot中配置参数
获取line属性的方法
line=plt.plot(x,y)plt.getp(line[0],'color')plt.setp(line[0],'color','r')plt.setp(line,'color','r')#setp可以对一组对象进行操作,getp只能操作一个
line有这些属性:
agg_filter = Nonealpha = Noneanimated = Falseantialiased or aa = Trueaxes = Axes(0.125,0.125;0.775x0.755)children = []clip_box = TransformedBbox(Bbox([[0.0, 0.0], [1.0, 1.0]]), Co...)clip_on = Trueclip_path = Nonecolor or c = #1f77b4contains = Nonedash_capstyle = buttdash_joinstyle = rounddata = (array([ 0. , 0.66666667, 1.33333333, 2....]))drawstyle = defaultfigure = Figure(432x288)fillstyle = fullgid = Nonelabel = $cos(x^2)$linestyle or ls = -linewidth or lw = 1.5marker = +markeredgecolor or mec = #1f77b4markeredgewidth or mew = 1.0markerfacecolor or mfc = #1f77b4markerfacecoloralt or mfcalt = nonemarkersize or ms = 6.0markevery = Nonepath = Path(array([[ 0., -0.],[ 0...]]))path_effects = []picker = Nonepickradius = 5rasterized = Nonesketch_params = Nonesnap = Nonesolid_capstyle = projectingsolid_joinstyle = roundtransform = CompositeGenericTransform(TransformWrapper(Blended...))transformed_clip_path_and_affine = (None, None)url = Nonevisible = Truexdata = [ 0. 0.66666667 1.33333333 2. ]xydata = [[ 0. -0. ] [ 0.66666667 -0.618369.]]ydata = [-0. -0.6183698 -0.9719379 -0.90929743 -...]zorder = 2
linestyle
'-'
solid line style '--'
dashed line style '-.'
dash-dot line style ':'
dotted line stylemarker
'.'
point marker点 ','
pixel marker一个像素点 'o'
circle marker实心圆 'v'
triangle_down marker '^'
triangle_up marker '<'
triangle_left marker '>'
triangle_right marker '1'
tri_down marker '2'
tri_up marker '3'
tri_left marker '4'
tri_right marker 's'
square marker方块 'p'
pentagon marker五边形 '*'
star marker五角星 'h'
hexagon1 marker六边形 'H'
hexagon2 marker横六边形 '+'
plus marker 'x'
x marker 'D'
diamond marker菱形 'd'
thin_diamond marker瘦菱形 “’ ‘“ '_'
hline marker横线color
line的其他参数
antialiased or aa: [True | False]axes: an :class:`~matplotlib.axes.Axes` instanceclip_box: a :class:`matplotlib.transforms.Bbox` instanceclip_on: [True | False]clip_path: [ (:class:`~matplotlib.path.Path`, :class:`~matplotlib.transforms.Transform`) | :class:`~matplotlib.patches.Patch` | None ]contains: a callable functiondash_capstyle: ['butt' | 'round' | 'projecting']dash_joinstyle: ['miter' | 'round' | 'bevel']dashes: sequence of on/off ink in pointsdrawstyle: ['default' | 'steps' | 'steps-pre' | 'steps-mid' | 'steps-post']figure: a :class:`matplotlib.figure.Figure` instancefillstyle: ['full' | 'left' | 'right' | 'bottom' | 'top' | 'none']gid: an id stringlabel: string or anything printable with '%s' conversion.linestylemarkeredgecolor or mec: any matplotlib colormarkeredgewidth or mew: float value in pointsmarkerfacecolor or mfc: any matplotlib colormarkerfacecoloralt or mfcalt: any matplotlib colormarkersize or ms: floatmarkevery: [None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]path_effects: unknownpicker: float distance in points or callable pick function ``fn(artist, event)``pickradius: float distance in pointsrasterized: [True | False | None]sketch_params: unknownsnap: unknownsolid_capstyle: ['butt' | 'round' | 'projecting']solid_joinstyle: ['miter' | 'round' | 'bevel']transform: a :class:`matplotlib.transforms.Transform` instanceurl: a url stringxdata: 1D arrayydata: 1D array
patch
bar()和hist()都是创建Patch对象列表
每个Patch列表中
n,bins,rects=ax.hist(...)
- 这里的rects是
- rects[0]是
import matplotlib.pyplot as pltfrom scipy.stats import normf1 = plt.figure(1)ax = plt.subplot(111)n, bins, rects = ax.hist(norm.rvs(loc=0, scale=1, size=100))rects
Axis
fig = plt.figure(1)ax = fig.add_subplot(111)line=ax.plot([1,2,3,4,5])xaxis=ax.xaxisplt.getp(xaxis)
可以获得它们的属性:
agg_filter = Nonealpha = Noneanimated = Falseaxes = Axes(0.125,0.11;0.775x0.77)children = [<matplotlib.text.Text object at 0x0000020033F2F78...>]clip_box = TransformedBbox(Bbox([[0.0, 0.0], [1.0, 1.0]]), Co...)clip_on = Trueclip_path = Nonecontains = Nonedata_interval = [ 0. 4.]figure = Figure(640x480)gid = Nonegridlines = <a list of 11 Line2D gridline objects>label = Text(0.5,0,'')label_position = bottomlabel_text =major_formatter = <matplotlib.ticker.ScalarFormatter>major_locator = <matplotlib.ticker.AutoLocator>major_ticks = [<matplotlib.axis.XTick>]majorticklabels = <a list of 11 Text major ticklabel objects>majorticklines = <a list of 22 Line2D ticklines objects>majorticklocs = [-0.5 0. 0.5 1. 1.5 2. ]...minor_formatter = <matplotlib.ticker.NullFormatter>minor_locator = <matplotlib.ticker.NullLocator>minor_ticks = []minorticklabels = <a list of 0 Text minor ticklabel objects>minorticklines = <a list of 0 Line2D ticklines objects>minorticklocs = []minpos = 1.0offset_text = Text(1,0,'')path_effects = []picker = Nonepickradius = 15rasterized = Nonescale = linearsketch_params = Nonesmart_bounds = Falsesnap = Nonetick_padding = 3.5tick_space = 11ticklabels = <a list of 11 Text major ticklabel objects>ticklines = <a list of 22 Line2D ticklines objects>ticklocs = [-0.5 0. 0.5 1. 1.5 2. ]...ticks_position = bottomtransform = IdentityTransform()transformed_clip_path_and_affine = (None, None)units = Noneurl = Noneview_interval = [-0.2 4.2]visible = Truezorder = 0
annotate
用来绘制带箭头的注释文字
annotate(s,xy,xytext,xycoords='data',textcoords='data',arrowprops=None)
- s:注释文本
- xy:箭头处的坐标
- xytext:注释文本的坐标
- xycoords&textcoords都是字符串, 解释在下表
test
用来绘制文字
ax.text(x,y,string,fontname='STKaiti',fontsize=20,color='r',transform=ax.transData)#数据坐标ax.text(x,y,string,fontname='STKaiti',fontsize=20,color='r',transform=ax.transAxes)#Axes内坐标,左下是(0,0),右上是(1,1)fig.text(x,y,string,fontname='STKaiti',fontsize=20,color='r',transform=ax.transData)#数据坐标fig.text(x,y,string,fontname='STKaiti',fontsize=20,color='r',transform=ax.transAxes)#Figure内坐标,左下是(0,0),右上是(1,1)
- fontname:字体,参见这里
阅读全文
0 0
- 【Python】【matplotlib】面向对象方式绘图
- matplotlib绘图案例: 面向对象绘画-折线图
- 绘图: Python matplotlib简介
- python使用matplotlib绘图
- python matplotlib包 绘图
- Python:使用Matplotlib绘图
- Python中Matplotlib绘图
- python使用matplotlib绘图
- python-matplotlib绘图
- Python--Matplotlib绘图库
- matplotlib python绘图
- python matplotlib绘图
- 【Python】【matplotlib】绘图
- 【Python】【matplotlib】绘图函数
- python中的matplotlib绘图问题
- python使用matplotlib绘图 -- barChart
- 【Python】Matplotlib绘图库初探
- python使用matplotlib绘图 -- barChart
- 符号配对
- sublime text 3 教程(2)
- Java IO流
- 项目管理师基础背诵
- 《UNIX网络编程 卷2》 笔记: 使用FIFO实现信号量
- 【Python】【matplotlib】面向对象方式绘图
- Eclipse中的Maven项目报错处理方法
- svn安装,配置
- 安卓 三个绘图工具类详解
- Eclipse中的Maven项目报错处理方法
- 心酸的Caffe安装之路 环境搭配 Ubuntu16.04+gtx1080+cuda8.0+cudnn5.1+opencv+Anaconda3+caffe
- rapidjson使用总结
- gradle android的依赖配置dependencies
- OpenResty 最佳实践学习--安装和helloworld(1)