6.3.1 图形Figure
Matplotlib中的"figure"表示用户界面中的整个窗口,一个figure对象是标题为"Figure#"的GUI窗口,Figure命名是以1开始,与以0开始索引的常规Python方式截然不同。这显然是Matlab风格。以下有几个参数确定figure对象的外观,如下表所示:
参数 | 默认值 | 描述 |
---|---|---|
num | 1 | 图形的数量 |
figsize | figure.figsize | 图形对象的宽度和高度(单位:英寸) |
dpi | figure.dpi | 像素分辨率 |
facecolor | figure.facecolor | 背景颜色 |
edgecolor | figure.edgecolor | 边界颜色 |
frameon | Ture | 是否绘制框架 |
默认值可以在源文件中指定,并且在大多数时间都会使用,只有图形的编号经常改变。
6.3.2 子图Axes
一个绘图对象(figure)可以包含多个子图(Axes),在Matplotlib中用Axes对象表示一个绘图区域。在前面的例子中,Figure对象只包括一个子图。可以使用subplot()函数快速绘制多个子图的图表。它的调用形式如下:
subplot(numRows, numCols, plotNum)
subplot将整个绘图区域等分为numRows行 * numCols列个子区域,然后按照从左到右,从上到下的顺序对每个子区域进行编号,左上的子区域的编号为1。plotNum参数指定所创建Axes对象的区域。如果numRows,numCols和plotNum这三个数都小于10的话,可以把它们缩写为一个整数,例如subplot(323)和subplot(3,2,3)是相同的。如果新创建的子图和之前创建的子图重叠,之前的子图将被删除。
下面的程序创建3行2列共6个子图,通过axisbg参数给每个轴设置不同的背景颜色。示例代码:
for idx, color in enumerate("rgbyck"):
plt.subplot(320+idx+1, axisbg=color)
plt.show()
显示结果:
![](https://img.haomeiwen.com/i5013892/2dc20899f6deb6c1.png)
通过创建figure对象,利用add_subplot()方法也可以创建若干子图,其参数与subplot()函数一致。拟构造了两个子图,按列并排显示,示例代码:
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax2 = fig.add_subplot(2,1,2)
plt.show()
显示结果:
![](https://img.haomeiwen.com/i5013892/d321bfd8451c0fa3.png)
此外,可以根据标号显示指定图像,示例代码:
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(3,2,1)
ax2 = fig.add_subplot(3,2,2)
ax6 = fig.add_subplot(3,2,6)
plt.show()
根据要求显示了三个图像,如图所示:
![](https://img.haomeiwen.com/i5013892/e23de64ecb503494.png)
可以绘制子图的不同图像,示例代码:
import numpy as np
fig = plt.figure()
#fig = plt.figure(figsize=(3, 3))
ax1 = fig.add_subplot(2,1,1)
ax2 = fig.add_subplot(2,1,2)
ax1.plot(np.random.randint(1,5,5), np.arange(5))
ax2.plot(np.arange(10)*3, np.arange(10))
plt.show()
显示结果:
![](https://img.haomeiwen.com/i5013892/6b0e22092f0208bf.png)
除了绘制不同的子图,在同一个子图中也可以绘制多个图表,示例代码:
import pandas as pd
import matplotlib.pyplot as plt
unrate = pd.read_csv("unrate.csv")
unrate['DATE'] = pd.to_datetime(unrate['DATE'])
unrate['MONTH'] = unrate['DATE'].dt.month
fig = plt.figure(figsize=(10, 6))
ax1 = fig.add_subplot(1,1,1)
colors = ['r', 'b', 'g', 'y', 'k']
for i in range(5):
start_index = i*12
end_index = (i+1)*12
subset = unrate[start_index:end_index]
label = str(1948+i)
ax1.plot(subset["MONTH"], subset["VALUE"], c=colors[i], label=label)
ax1.legend(loc="upper left")
plt.xlabel("Month, Integer")
plt.ylabel("Unemployment Rate, Percent")
plt.title("Monthly Unemployment Trends, 1948-1952")
plt.show()
显示结果:
![](https://img.haomeiwen.com/i5013892/4effdb4d5b2ca41b.png)
6.3.3 坐标Axis容器
Axis容器包括坐标轴上的刻度线、刻度文本、坐标网格以及坐标轴标题等内容。每个刻度线都是一个XTick或YTick对象,它包括实际的刻度线和刻度文本。
下面先创建一个子图并获得其X轴对象axis:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
axis = ax.xaxis
下面获得axis对象的刻度位置的列表:
axis.get_ticklocs()
运行结果:
array([ 0. , 0.2, 0.4, 0.6, 0.8, 1. ])
下面获得axis对象的刻度标签以及标签中的文字:
print(axis.get_ticklabels()) # 获得刻度标签的列表
print([x.get_text() for x in axis.get_ticklabels()]) # 获得刻度的文本字符串
运行结果:
<a list of 6 Text major ticklabel objects>
下面获得轴上表示主刻度线的列表,可以看到X轴上共有12条刻度线,它们是子图的上下两个X轴上的所有刻度线:
axis.get_ticklines()
<a list of 12 Line2D ticklines objects>
由于图中没有副刻度线,因此副刻度线列表的长度为0:
axis.get_ticklines(minor=True) # 获得副刻度线列表
<a list of 0 Line2D ticklines objects>
获得刻度线或刻度标签之后,可以设置其各种属性,下面设置刻度线为绿色粗线,文本为红色并且旋转45°。示例代码:
for label in axis.get_ticklabels():
label.set_color("red")
label.set_rotation(45)
label.set_fontsize(16)
for line in axis.get_ticklines():
line.set_color("green")
line.set_markersize(25) # 设置刻度线长度
line.set_markeredgewidth(3) # 设置刻度线宽度
fig
显示结果
使用pyplot模块中的xticks()能够快速的完成X轴上的刻度文本的配置。不过,xticks()只能设置刻度文本的属性,不能设置刻度线的属性。示例代码:
plt.xticks(fontsize=16, color="red", rotation=45)
网友评论