http://old.sebug.net/paper/books/scipydoc/matplotlib_intro.html
matplotlib 属于第三方库,首先安装:pip install matplotlib
我用的是 pylab 模式下的 ipython : ipython --pylab
matplotlib API 函数都位于matplotlib.pylot 模块下,导入:import matplotlib.pylot as plt
Figure 和 subplot
matplotlib 的图像都位于 Figure 对象中,空的 Figure 不能再上面绘图,所以我们要在上面添加很多subplot(子图)来绘图。在 Figure 对象中添加子图的方式有多种:
1)i:首先创建一个 Figure 对象: fig = plt.figure()
ii:通过 add_subplot 创建 subplot:ax1 = fig.add_subplot(2, 2, 1) # 在空的 Figure 上添加 2*2 (2行2列) 个子图,
# 这是第一个子图,第二个:ax1 = fig.add_subplot(2, 2, 2)
# 也可以这样写 ax1 = fig.add_subplot(221)
iii:绘图, ax1.plot(...) # 也可以绘制其他图形,例如:直线,柱状...。因为 matplotlib 默认操作当前子图,
所以也可以使用全局对象绘图 plt.plot(...)
2) 创建 Figure 对象这步可以省去:plt.subplot(2, 2, 1) ...
3) figure, ax = plt.subplots(2, 2) # 创建 2 * 2 (2行2列) 个子图。ax[0][0] 第一个子图 ...
下面就是一些绘制图的细节问题:
xlabel,ylabel:设置横纵坐标轴的标签
legend: 设置图例
#legend 的位置参数
'''
best
upper right
upper left
lower left
lower right
right
center left
center right
lower center
upper center
center
'''
title:设置子图的标题
suptitle:设置所有子图的标题
text:设置文本说明
xticks,yticks:设置横纵轴的坐标标签
xlim,ylim:设置横纵轴的刻度范围
annotate:添加注解
grid:添加网格
savefig:保存图片
看几个例子:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
matplotlib图标正常显示中文
为了在图表中能够显示中文和负号等,需要下面一段设置:
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
例1:
put_x = np.arange(0.0, 2.0, 0.1)
sin_ = np.sin(put_x * np.pi)
plt.subplot(2, 2, 1) # 生成两行两列,2 * 2 个子图,这是第一个图plt.subplot('行','列','编号')
plt.plot(put_x, sin_, 'b--')
plt.ylabel('y1')
plt.subplot(2, 2, 2) # 两行两列,这是第二个图
plt.plot(2 * put_x, sin_, 'r--')
plt.ylabel('y2')
plt.subplot(2, 2, 3) # 两行两列,这是第三个图
plt.plot(3 * put_x, sin_, 'm--')
plt.subplot(2, 2, 4) # 两行两列,这是第四个图
plt.plot(4 * put_x, sin_, 'k--')
plt.show()
例2:
fig = plt.figure()
fig.add_subplot(2, 2, 1) # 生成两行两列,2 * 2 个子图,这是第一个图plt.subplot('行','列','编号')
plt.plot(put_x, sin_, 'b--')
plt.ylabel('y1')
fig.add_subplot(2, 2, 2) # 两行两列,这是第二个图
plt.plot(2 * put_x, sin_, 'g*')
plt.plot(put_x, sin_, 'r--')
plt.legend(['this is a label', 'the second label'], loc='upper right')
plt.title('text')
plt.ylabel('y2')
plt.xlabel('x2')
plt.text(2, 2, "I'm a Test")
plt.xticks([0, 1, 2, 3, 4])
plt.yticks([0, 1, 2, 3, 4])
plt.xlim(0, 8)
plt.annotate("I'm a annotation", xy=(1, 1), xytext=(2, 1), # xy 箭头指向, xytext 注解文本所在位置
arrowprops=dict(facecolor='black'))
plt.suptitle('supTitle')
plt.grid()
fig.add_subplot(2, 2, 3) # 两行两列,这是第三个图
plt.plot(3 * put_x, sin_, 'm--')
fig.add_subplot(2, 2, 4) # 两行两列,这是第四个图
plt.plot(4 * put_x, sin_, 'k--')
plt.savefig('savefig.png')
plt.show()
例3::
figure, ax = plt.subplots(2, 2) # 创建 2 * 2 个子图
print(ax)
ax[0][0].plot(put_x, sin_, 'r*') # 第一个子图
ax[0][1].plot(put_x * 2, sin_, 'b--') # 第二个子图, [1][0] 第三个,[1][1] 第四个
ax[1][0].scatter(np.arange(30), np.arange(30) + 3 * np.random.randn(30))
plt.show()
例4:
dates = list('ABCDEFG')
datas = np.arange(7)[::-1]
df = pd.DataFrame(datas, index=dates, columns=['Numbers'])
plt.subplot(111)
plt.plot(df.index, df['Numbers'].values, 'b--')
plt.title('Just a Test')
plt.ylabel('numbers')
plt.xlabel('Date')
plt.annotate("I'm a annotation", xy=(2, 4), xytext=(3, 6),
arrowprops=dict(facecolor='r'))
plt.show()
例5::
nums = [384, 551, 176, 1628, 420, 174, 1051, 2067, 624, 1471, 238, 433, 1039, 3555]
labels = ['Excel', 'Hadoop', 'matlab', 'mysql', 'nosql', 'oracle', 'python', 'R',
'SAS', 'sql', 'SPSS', 'DataDig', 'ML', 'PC']
df1 = pd.DataFrame(nums, index=labels, columns=['Numbers'])
df1.index.name = 'topics'
plt.figure(figsize=(10, 6))
# 设置x轴柱子的个数
x = np.arange(14) + 1 # 课程品类数量已知为14,也可以用len(ppv3.index)
# 设置y轴的数值,需将numbers列的数据先转化为数列,再转化为矩阵格式
y = df1['Numbers'].values
x_ticks = df1.index.values # 构造不同课程类目的数列
# 画出柱状图
plt.bar(x, y, width=0.35, align='center', color='c', alpha=0.8)
# 设置x轴的刻度,将构建的x_ticks代入,同时由于课程类目文字较多,在一块会比较拥挤和重叠,因此设置字体和对齐方式
plt.xticks(x, x_ticks, size='small', rotation=30)
# x、y轴标签与图形标题
plt.xlabel('Classes subject')
plt.ylabel('Number')
plt.title('diff classes mean num')
# 设置数字标签**
for a, b in zip(x, y):
plt.text(a, b + 0.05, '%.0f' % b, ha='center', va='bottom', fontsize=7)
# 设置y轴的范围
plt.ylim(0, 3700)
plt.show()
例6:
fig = plt.figure()
ax = fig.add_subplot(111)
rect = plt.Rectangle((0.2, 0.75), 0.4, 0.15, color='k', alpha=0.3)
circ = plt.Circle((0.7, 0.2), 0.15, color='b', alpha=0.3)
pgon = plt.Polygon([[0.15, 0.15], [0.35, 0.4], [0.2, 0.6]],
color='g', alpha=0.5)
ax.add_patch(rect)
ax.add_patch(circ)
ax.add_patch(pgon)
plt.show()
下面的字符用来描述绘制的图形:
字符 | 描述 |
'-' | 实线 |
'--' | 虚线 |
'-.' | 点线 |
':' | 点虚线 |
'.' | 点 |
',' | 像素 |
'o' | 圆形 |
'v' | 朝下的三角形 |
'^' | 朝上的三角形 |
'<' | 朝左的三角形 |
'>' | 朝右的三角形 |
'1' | tri_down marker |
'2' | tri_up marker |
'3' | tri_left marker |
'4' | tri_right marker |
's' | 正方形 |
'p' | 五角形 |
'*' | 星型 |
'h' | 1号六角形 |
'H' | 2号六角形 |
'+' | +号标记 |
'x' | x号标记 |
'D' | 钻石形 |
'd' | 小版钻石形 |
'|' | 垂直线形 |
'_' | 水平线行 |
颜色用以下字符表示:
字符 | 颜色 |
‘b’ | 蓝色 |
‘g’ | 绿色 |
‘r’ | 红色 |
‘c’ | 青色 |
‘m’ | 品红 |
‘y’ | 黄色 |
‘k’ | 黑色 |
‘w’ | 白色 |