python-matplotlib-lec1

接演前文。


设置属性的方法:

  • 使用对象的set_*方法,单独设置每个属性;或使用plt.setp同时设置多个属性
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt

# set range 0~5, step = 0.1
x = np.arange(0, 5, 0.1)
# plot return a list. only get first element as 'line'
line, = plt.plot(x, x*x)
# set_antialiased = True, smoother
line.set_antialiased(False)
plt.show()

# lines has 2 lines.
lines = plt.plot(x, np.sin(x), x, np.cos(x))
plt.setp(lines, color="r", linewidth=2.0)
plt.show()

  同时,可以使用get_*或者plt.getp来获取对象的属性值。

print line.get_linewidth()
# getp only operates on one object each time
print plt.getp(lines[1])
# given parameter
print plt.getp(lines[0], "color")
# get current figure object. It's returned by plt.plot.
cur = plt.gcf()
# although cur is a list, cannot be indexed in getp. 
plt.getp(cur)

  Figure对象有一个axes属性,值为AxesSubplot对象列表,即图中的每个子图。获得当前的子图应使用

plt.gca()

  要在Figure对象中放多个子图(轴,axes),应使用subplot(nRows, nCols, plotNum)。图的编号从1开始,从左到右,从上到下。如果这三个参数都小于10,

可以写成整数。subplot在编号为plotNum的区域中创建子图,新的会覆盖旧的。另外,可以用图中的配置按钮配置left.right.top等几个参数。

  举个栗子咯,下面的代码会创建3*2的图,设置指定背景颜色。

plt.figure(1)
for idx, color in enumerate("rgbyck"):
    plt.subplot(320+idx+1, axisbg=color)
plt.show()

  如果需要某个轴占据整行:

plt.subplot(221)
plt.subplot(222)
# 2*1, so position 2 is the whole second row space
plt.subplot(212)

可以通过修改配置文件调整缺省值,批量修改属性。相关方法见网页。

http://old.sebug.net/paper/books/scipydoc/matplotlib_intro.html#id5


matplotlib API含三层,backend_bases.FigureCanvas,backend_bases.Renderer和artist.Artist。一般只使用高层的Artist。

它分为两种,简单类型为标准绘图元件,如Line2D、Rectangle之类的,容器类型则是将简单的合成一个整体,如Figure、Axis等。

一般流程:创建Figure对象--->创建Axes--->创建简单类型的Artist


Artist对象的所有属性都通过相应的 get_* 和 set_* 函数进行读写

一次设置多个属性,set函数:fig.set(alpha=0.5, zorder=2)

属性列表:

alpha : 透明度,值在0到1之间,0为完全透明,1为完全不透明
animated : 布尔值,在绘制动画效果时使用
axes : 此Artist对象所在的Axes对象,可能为None
clip_box : 对象的裁剪框
clip_on : 是否裁剪
clip_path : 裁剪的路径
contains : 判断指定点是否在对象上的函数
figure : 所在的Figure对象,可能为None
label : 文本标签
picker : 控制Artist对象选取
transform : 控制偏移旋转
visible : 是否可见
zorder : 控制绘图顺序

figure对象和Axes对象都有patch属性作为其背景,它的值是一个Rectangle对象。注意,刚设置完patch的颜色后,要用.canvas.draw()更新。

fig = plt.figure(1)
# left, bottom, width, height. relative to figure object. 0-1
ax = fig.add_axes([0.15, 0.5, 0.7, 0.3])
# draw a line
lines = ax.plot([1,2,3],[1,2,1])
ax.set_xlabel("time")
fig.patch.set_color("g")
fig.canvas.draw()
fig.show() 

Figure对象

fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.3])
# subplot and axes are added to Figure.axes
# don't operate on Figures.axes directly, use
# add_subplot, add_axes, delaxes etc.
# But iteration is ok.
for ax in fig.axes: ax.grid(True)
plt.show()  

在Figure对象中画两条线:

from matplotlib.lines import Line2D
fig = plt.figure()
# 缺省的坐标系统是像素点,但可以通过transform来修改坐标系(缺省是左下角原点(0,0),右上角(1,1))。
# 此处两条线用的都是fig的,它们所在的figure对象也是fig
# Line2D([xdata],[ydata]...)
lin1 = Line2D([0,1], [0,1], transform=fig.transFigure, figure=fig, color="r")
lin2 = Line2D([0,1], [1,0], transform=fig.transFigure, figure=fig, color="g")
# 将两条线添加到fig.lines属性中
fig.lines.extend([lin1, lin2])
plt.show()  

包含Artist对象的属性:

axes : Axes对象列表
patch : 作为背景的Rectangle对象
images : FigureImage对象列表,用来显示图片
legends : Legend对象列表
lines : Line2D对象列表
patches : patch对象列表
texts : Text对象列表,用来显示文字

Axes容器

fig = plt.figure()
ax = fig.add_subplot(111)
# axes对象ax有patch属性作为背景。笛卡尔坐标时,patch为Rectangle对象;极坐标时,为Circle对象。
# 设置背景为蓝色。
ax.patch.set_facecolor("blue")
# fig.show() 会闪退
plt.show()  

一般不对Axes所带的lines或patch直接操作


Axis容器

包括坐标轴上的刻度线、刻度文本、坐标网格以及坐标轴标题等内容。刻度包括主刻度和副刻度,分别通过Axis.get_major_ticks和Axis.get_minor_ticks方法获得。

每个刻度线都是一个XTick或者YTick对象,它包括实际的刻度线和刻度文本。为了方便访问刻度线和文本,Axis对象提供了get_ticklabels和get_ticklines方法。

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
sub1 = fig.add_subplot(1,2,1)
sub1.plot([1,2,3], [4,5,6])

xAxis = fig.gca().xaxis
# values of ticks on x-axis
print xAxis.get_ticklocs()
# show ticklabels. but now, it's empty
print [x.get_text() for x in xAxis.get_ticklabels()]
# set ticklabels
for label in xAxis.get_ticklabels():
    label.set_color("red")
    label.set_rotation(45)
    label.set_fontsize(16)
# get minor ticklines
# get_ticklines(minor=True)
for line in xAxis.get_ticklines():
    line.set_color("green")
    line.set_markersize(25)
    line.set_markeredgewidth(3)
plt.show()

关于刻度的定位和文本格式的东西都在matplotlib.ticker中定义,程序中使用到如下两个类:

MultipleLocator : 以指定值的整数倍为刻度放置刻度线

FuncFormatter : 使用指定的函数计算刻度文本,他会传递给所指定的函数两个参数:刻度值和刻度序号

# 主刻度为pi/4
ax.xaxis.set_major_locator( MultipleLocator(np.pi/4) )

# 主刻度文本用pi_formatter函数计算
ax.xaxis.set_major_formatter( FuncFormatter( pi_formatter ) )

# 副刻度为pi/20
ax.xaxis.set_minor_locator( MultipleLocator(np.pi/20) )

  

  

原文地址:https://www.cnblogs.com/pxy7896/p/6952956.html