matplotlib教程學(xué)習(xí)筆記
基本
有倆種Artist:primitives(圖形元素)和containers(容器)的畴。primitives是我們需要加入圖片的元素,比如線條足淆,矩形巢块,文字等,而容器是放置這些元素的地方巧号,比如Axis,Axes和Figure族奢。標(biāo)準(zhǔn)的用法,應(yīng)該是先建立一個(gè)Figure對(duì)象丹鸿,再創(chuàng)建數(shù)個(gè)Axes對(duì)象越走,然后再添加圖形元素。
plt.figure()
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(2, 1, 1) #倆行一列, ax為第一個(gè)Plot
Axes是最多使用的靠欢,大部分圖形元素都會(huì)添加于其中廊敌,我們可以利用add_axes()來(lái)隨時(shí)隨地添加Axes。
fig.add_axes()
fig2 = plt.figure()
ax2 = fig2.add_axes([0.15, 0.1, 0.6, 0.5]) #[left right width height]
繼續(xù)畫圖:
ax.lines
t = np.arange(0, 1, 0.01)
s = np.sin(2*np.pi*t)
line, = ax.plot(t, s, color="blue", lw=2)
在這個(gè)例子中门怪,ax是Axes實(shí)例骡澈,通過(guò)fig.add_subplot創(chuàng)建(subplot是Axes的一個(gè)子類),當(dāng)你運(yùn)行ax.plot的時(shí)候掷空,它創(chuàng)建了一個(gè)Line2D實(shí)例肋殴,并將此元素添加到Axes.lines.list中,從下面我們可以看到坦弟,這個(gè)線疼电,與返回得到的線line是一樣的:
print(line, ax.lines[0]) # Line2D(_line0) Line2D(_line0)
既然Line2D實(shí)例被添加到了ax.lines列表中,那么我們也可以通過(guò)對(duì)列表進(jìn)行操作來(lái)移除該實(shí)例:
del ax.lines[0]
ax.lines.remove(line)
set_xlabel
Axes也可以來(lái)修飾坐標(biāo)軸减拭,比如添加坐標(biāo)軸的名稱:
xtext = ax.set_xlabel("my xdata")
ytext = ax.set_ylabel("my ydata")
當(dāng)我們使用set_xlabel的時(shí)候蔽豺,它將數(shù)據(jù)傳入XAxis的Text實(shí)例(每個(gè)Axes都有一個(gè)XAxis和YAxis實(shí)例)。
一個(gè)完整的例子
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
fig.subplots_adjust(top=0.8)
ax1 = fig.add_subplot(211) #2row 1col 第一個(gè)plot
ax1.set_ylabel("volts")
ax1.set_title("a sin wave")
t = np.arange(0, 1, 0.01)
s = np.sin(2*np.pi*t)
line, = ax1.plot(t, s, color="blue", lw=2)
np.random.seed(10086)
ax2 = fig.add_axes([0.15, 0.1, 0.7, 0.3])
n, bins, patches = ax2.hist(np.random.randn(1000), 50,
facecolor="yellow", edgecolor="yellow")
ax2.set_xlabel('time (s)')
plt.show()
定制你的對(duì)象
obj.set(alpha=0.5, zorder=2), obj.set_alpha(0.5)
我們可以通過(guò)obj.set(alpha=0.5, zorder=2)等以此設(shè)置多個(gè)屬性拧粪,也可以通過(guò)obj.set_alpha(0.5)設(shè)定alpha一個(gè)屬性修陡。
Artist實(shí)例有一系列屬性沧侥,通過(guò)對(duì)屬性的調(diào)整可以達(dá)到個(gè)性化的目的,下面是一個(gè)表:
相關(guān)信息被存放在figure.patch和ax.patch中魄鸦,我們可以通過(guò)matplotlib.artist.getp()來(lái)查閱
matplotlib.artist.getp(), plt.getp()
通過(guò)下列語(yǔ)句都能獲得line的alpha屬性:
import matplotlib
plt.getp(line, "alpha")
plt.matplotlib.artist.getp(line, "alpha")
通過(guò)下列語(yǔ)句獲得全部屬性:
print(matplotlib.artist.getp(fig.patch)) #直接fig也可以啊宴杀,為什么一定要fig.patch?
agg_filter = None
alpha = None
animated = False
antialiased = False
bbox = Bbox(x0=0.0, y0=0.0, x1=1.0, y1=1.0)
capstyle = butt
children = []
clip_box = None
clip_on = True
clip_path = None
contains = None
data_transform = BboxTransformTo( TransformedBbox( Bbox...
edgecolor = (1.0, 1.0, 1.0, 1.0)
extents = Bbox(x0=0.0, y0=0.0, x1=640.0, y1=480.0)
facecolor = (1.0, 1.0, 1.0, 1.0)
figure = Figure(640x480)
fill = True
gid = None
hatch = None
height = 1
in_layout = True
joinstyle = miter
label =
linestyle = solid
linewidth = 0.0
patch_transform = CompositeGenericTransform( BboxTransformTo( ...
path = Path(array([[0., 0.], [1., 0.], [1.,...
path_effects = []
picker = None
rasterized = None
sketch_params = None
snap = None
transform = CompositeGenericTransform( CompositeGenericTra...
transformed_clip_path_and_affine = (None, None)
url = None
verts = [[ 0. 0.] [640. 0.] [640. 480.] [ 0. 480....
visible = True
width = 1
window_extent = Bbox(x0=0.0, y0=0.0, x1=640.0, y1=480.0)
x = 0
xy = (0, 0)
y = 0
zorder = 1
None
也可以通過(guò)查閱某個(gè)對(duì)象的屬性:
print(matplotlib.artist.getp(line))
直接用
print(plt.getp(line))
也是可以的,雖然好像有一丟丟的不一樣拾因。
容器
正如我們之前提到的旺罢,Artist包括圖形元素和容器。容器和圖形元素有類似的屬性绢记,也有一些特別的 扁达,不如可以通過(guò)xscale屬性來(lái)控制x軸為線性的還是'log'的。這一節(jié)蠢熄,我們將回顧有關(guān)不同容器對(duì)象的一些方法跪解。
Figure container
最底層(top level)的容器便是figure對(duì)象,它包含一切在figure中的元素签孔。其背景為Rectangle,被存放在Figure.patch中叉讥。當(dāng)你通過(guò)add_subplot()或者add_axes()創(chuàng)建實(shí)例的時(shí)候,這些元素會(huì)被自動(dòng)添加到饥追,F(xiàn)igure.axes中图仓。
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_axes([0.1, 0.2, 0.7, 0.3])
ax1
#<matplotlib.axes._subplots.AxesSubplot at 0x1e734b47f28>
ax2
#<matplotlib.axes._axes.Axes at 0x1e734de6908>
print(fig.axes)
#[<matplotlib.axes._subplots.AxesSubplot object at 0x000001E734B47F28>,
#<matplotlib.axes._axes.Axes object at 0x000001E734DE6908>]
我們可以通過(guò)fig.gca或者fig.sca來(lái)獲得當(dāng)前的axes,也可以通過(guò)delaxes()方法來(lái)移除但绕。
print(fig.gca()) # Axes(0.1, 0.2; 0.7x0.3)
plt.delaxes(ax2)
print(fig.gca()) # AxesSubplot(0.125,0.536818;0.775x0.343182)
圖片有用自己的text, lines, patches, images, 你可以直接往里面添加圖片元素救崔。
圖片坐標(biāo)(0, 0)代表左下角, (1壁熄,1)代表右上角帚豪?
import matplotlib.lines as lines
fig = plt.figure()
l1 = lines.Line2D([0, 1], [0, 1], transform=fig.transFigure, figure=fig)
l2 = lines.Line2D([0, 1], [1, 0], transform=fig.transFigure, figure=fig)
fig.lines.extend([l1, l2]) #extend是列表的方法
plt.show()
Axes container
Axes是matplotlib的重中之重,它包含了卻大多數(shù)的Artist草丧。和Figure一樣狸臣,它包含patch——Rectangle:笛卡爾坐標(biāo)和Circle:極坐標(biāo)。
fig = plt.figure()
ax = fig.add_subplot(211)
rect = ax.patch # a Rectangle instance
rect.set_facecolor('green')
ax2 = fig.add_subplot(212, projection='polar')
cir = ax2.patch
cir.set_facecolor('yellow')
plt.show()
當(dāng)你使用plotting method的時(shí)候昌执,比如plot()烛亦,傳入arrays,這個(gè)方法會(huì)創(chuàng)建了一個(gè)matplotlib.lines.Line2D()實(shí)例懂拾,并利用參數(shù)加以更新煤禽,然后將lines加入Axes.lines容器,并將他返回給你岖赋。
x, y = np.random.rand(2, 100)
line = ax.plot(x, y, "-", color="blue", linewidth=2)
print(ax.lines)
# [<matplotlib.lines.Line2D object at 0x000002A965ED88D0>]
bar()檬果,hist()也有相似的功能,會(huì)添加patches到Axes.patches列表中。
下面的n表示每個(gè)柱patch的高度选脊,bins是指所在的位置杭抠,而rectangles是Rectangle實(shí)例列表。
n, bins, rectangles = ax.hist(np.random.randn(1000), 50, facecolor="yellow")
for item in rectangles[10:20]:
item.set_facecolor("red")
item.set_edgecolor((1.0, 1.0, 1.0, 1.0))
plt.show()
一般情況下恳啥,請(qǐng)不要將之間向Axes.lines和Axes.patches中添加實(shí)例偏灿,除非你非常確定要這么做。因?yàn)槎鄣模谔砑訉?shí)例前翁垂,Axes會(huì)做一些額外的事情:它會(huì)設(shè)置一些屬性,檢查Artist中的數(shù)據(jù)硝桩,并自動(dòng)改變Axes的布局沿猜。我們可以通過(guò)add_line(),add_patch()來(lái)添加元素。
本來(lái)這里應(yīng)該有一個(gè)完整的實(shí)例的亿柑,但是obj.get_axes()函數(shù)被移除了邢疙,所以沒(méi)辦法了棍弄,貼一下方法:
Axis container
matplotlib.axis.Axis實(shí)例處理軸和網(wǎng)格線望薄,以及上面的標(biāo)記。
fig, ax = plt.subplots()
axis = ax.xaxis
print(axis.get_ticklocs())
print(axis.get_ticklabels())
print(axis.get_ticklines())
print(axis.get_ticklines(minor=True))
#[0. 0.2 0.4 0.6 0.8 1. ]
#<a list of 6 Text major ticklabel objects>
#<a list of 12 Line2D ticklines objects>
#<a list of 0 Line2D ticklines objects>
一個(gè)關(guān)于Axis的完整的例子(+常用的函數(shù))
# Here is a summary of some of the useful accessor methods of the ``Axis``
# (these have corresponding setters where useful, such as
# set_major_formatter)
#
# ====================== =========================================================
# Accessor method Description
# ====================== =========================================================
# get_scale The scale of the axis, e.g., 'log' or 'linear'
# get_view_interval The interval instance of the axis view limits
# get_data_interval The interval instance of the axis data limits
# get_gridlines A list of grid lines for the Axis
# get_label The axis label - a Text instance
# get_ticklabels A list of Text instances - keyword minor=True|False
# get_ticklines A list of Line2D instances - keyword minor=True|False
# get_ticklocs A list of Tick locations - keyword minor=True|False
# get_major_locator The matplotlib.ticker.Locator instance for major ticks
# get_major_formatter The matplotlib.ticker.Formatter instance for major ticks
# get_minor_locator The matplotlib.ticker.Locator instance for minor ticks
# get_minor_formatter The matplotlib.ticker.Formatter instance for minor ticks
# get_major_ticks A list of Tick instances for major ticks
# get_minor_ticks A list of Tick instances for minor ticks
# grid Turn the grid on or off for the major or minor ticks
# ====================== =========================================================
#
# Here is an example, not recommended for its beauty, which customizes
# the axes and tick properties
# plt.figure creates a matplotlib.figure.Figure instance
fig = plt.figure()
rect = fig.patch # a rectangle instance
rect.set_facecolor('lightgoldenrodyellow')
ax1 = fig.add_axes([0.1, 0.3, 0.4, 0.4])
rect = ax1.patch
rect.set_facecolor('lightslategray')
for label in ax1.xaxis.get_ticklabels():
# label is a Text instance
label.set_color('red')
label.set_rotation(45)
label.set_fontsize(16)
for line in ax1.yaxis.get_ticklines():
# line is a Line2D instance
line.set_color('green')
line.set_markersize(25)
line.set_markeredgewidth(3)
plt.show()
Tick containers
Tick是最后的容器呼畸,包含了軸和網(wǎng)格線實(shí)例痕支。
一個(gè)關(guān)于Tick的例子
# sphinx_gallery_thumbnail_number = 10
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
# Fixing random state for reproducibility
np.random.seed(19680801)
fig, ax = plt.subplots()
ax.plot(100*np.random.rand(20))
formatter = ticker.FormatStrFormatter('$%1.2f')
ax.yaxis.set_major_formatter(formatter)
for tick in ax.yaxis.get_major_ticks():
tick.label1On = True
tick.label2On = True
tick.label2.set_color('green')
plt.show()
函數(shù)鏈接
add_axes()-添加axes
set_xlabel()-添加xlabel
matplotlib.artist.getp()-獲取屬性類似的plt.getp()
Rectangle-figure的背景
add_subplot()-添加subplot
fig.gca()-獲取當(dāng)前的axes
plt.delaxes(ax)-移除ax
ax.add_line()-添加line
ax.add_patches()-添加patches