Matplotlib新手上路(上)
matplotlib是python里用于绘图的专用包,功能十分强大。下面介绍一些最基本的用法:
一、最基本的划线
先来一个简单的示例,代码如下,已经加了注释:
import matplotlib.pyplot as plt
import numpy as np
# 先获取一个图表
plt.figure()
# 设置图表的标题
plt.title("sale report")
# 设置y轴的label标签
plt.ylabel("amount")
# 设置x轴的label标签
plt.xlabel("month")
# 模拟一些(X,Y)坐标数据(注:习惯上用大写表示矩阵)
X = np.arange(0, 13)
Y = np.array([100, 200, 200, 300, 400, 600, 500, 550, 600, 700, 800, 750, 800])
# 将x轴的刻度范围限制为-0.5~12.2
plt.xlim(-0.5, 12.2)
# 将y轴的刻度范围限制为0~1000
plt.ylim(0, 1000)
# 将(X,Y)坐标用red红色画线
plt.plot(X, Y, 'r')
# X坐标也可以省略,只要Y轴的坐标值即可,--表示是虚线
plt.plot(Y + 50, '--')
# g+表示green绿色,画图的样式为+号
plt.plot(Y - 50, 'g+')
# 同时划二条线,第1个是yellow黄色,第2个是magenta色,另外还设置了样式1
plt.plot(Y - 100, 'y', Y - 150, 'm1')
# 渲染出来
plt.show()
注:plt中有很多缩写,比如r代表red,y代表yellow,xlim即x-axis-limit(x轴的限制),另外g+,表示颜色是green,而后面的+号表示划线的样式。从源码中可以找到更多的缩写说明。 matplotlib/axes/_axes.py 在这个文件中,plot方法的注释里有相关描述:
1 The following format string characters are accepted to control 2 the line style or marker: 3 4 ================ =============================== 5 character description 6 ================ =============================== 7 ``'-'`` solid line style 8 ``'--'`` dashed line style 9 ``'-.'`` dash-dot line style 10 ``':'`` dotted line style 11 ``'.'`` point marker 12 ``','`` pixel marker 13 ``'o'`` circle marker 14 ``'v'`` triangle_down marker 15 ``'^'`` triangle_up marker 16 ``'<'`` triangle_left marker 17 ``'>'`` triangle_right marker 18 ``'1'`` tri_down marker 19 ``'2'`` tri_up marker 20 ``'3'`` tri_left marker 21 ``'4'`` tri_right marker 22 ``'s'`` square marker 23 ``'p'`` pentagon marker 24 ``'*'`` star marker 25 ``'h'`` hexagon1 marker 26 ``'H'`` hexagon2 marker 27 ``'+'`` plus marker 28 ``'x'`` x marker 29 ``'D'`` diamond marker 30 ``'d'`` thin_diamond marker 31 ``'|'`` vline marker 32 ``'_'`` hline marker 33 ================ =============================== 34 35 36 The following color abbreviations are supported: 37 38 ========== ======== 39 character color 40 ========== ======== 41 'b' blue 42 'g' green 43 'r' red 44 'c' cyan 45 'm' magenta 46 'y' yellow 47 'k' black 48 'w' white 49 ========== ========
二、绘制数学函数
下面是抛物线、直线、三角函数的演示:
import matplotlib.pyplot as plt
import numpy as np
# 先获取一个图表
fig = plt.figure()
# 抛物线
X1 = np.linspace(-5, 5, 50) # -5 ~ 5 之间生成50个点
Y1 = X1 ** 2 + 5
plt.plot(X1, Y1, 'r')
# plt.plot(X1, Y1, color='red', label='parabola')
# 三角函数
X2 = np.linspace(np.pi, 5 * np.pi, 50) # 在pi ~ 5pi之间生成50个点
Y2 = 6 * np.cos(X2)
plt.plot(X2, Y2, 'y')
# plt.plot(X2, Y2, color='y', label='cosine')
# 直线
X3 = np.linspace(-4, 6, 20)
Y3 = 3 * X3 + 10
plt.plot(X3, Y3, 'g--')
# plt.plot(X3, Y3, color='green', linestyle='--', label='line')
# 显示图例说明
# plt.legend()
# 渲染出来
plt.show()
注意:代码中有一些行被注释掉了,比如:plt.plot(X1, Y1, color='red', label='parabola') ,这其实是 plt.plot(X1, Y1, 'r') 的完整写法,其中label只有完整写法中才能指定。换成完整写法后,同时把plt.legend() 前面的注释去掉,再次运行图上就会显示出所谓的"图例"
三、坐标轴控制、文本注解显示
先看效果图:
代码如下:
# coding:utf8
import matplotlib.pyplot as plt
import numpy as np
# 先获取一个图表
fig = plt.figure()
# 设置x,y坐标轴的刻度显示范围
plt.xlim(-7, 7)
plt.ylim(0, 7)
# 抛物线
X1 = np.linspace(-5, 5, 50) # -5 ~ 5 之间生成50个点
Y1 = 0.25 * X1 ** 2
plt.plot(X1, Y1, color='red', label=r'$y=\frac{x^2}{4}$')
# 直线
X2 = np.linspace(-5, 5, 50)
Y2 = X2
plt.plot(X2, Y2, color='green', linestyle='--', label=r'$y=x$')
# 黑色辅助线
plt.plot([4, 4], [4, 0], "k--")
# 抛物线与直线的交点处,标记1个黑点
plt.plot([4, 4], [4, 4], 'ko')
# 交点处的文本(annotate方式)
plt.annotate(r'$y=\frac{4^2}{4}=4$',
xy=(4, 4),
xycoords='data',
xytext=(+10, -30),
textcoords='offset points',
fontsize=12,
color="red",
arrowprops=dict(arrowstyle="->",
color="red",
connectionstyle="arc3,rad=.5"))
# text方式的文本
plt.text(5.2, 6.1, r'$y=\frac{x^2}{4}$', fontdict={'size': 16, 'color': 'r'})
plt.text(5.2, 5.1, r'$y=x$', fontdict={'size': 16, 'color': 'g'})
# 获取当前坐标轴gca即get current axis
ax = plt.gca()
# 去掉上、右二侧的边框线
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
# 将左侧的y轴,移到x=0的位置
ax.spines['left'].set_position(('data', 0))
# 调整x轴刻度(从-5到+5,正好11个点)
plt.xticks(np.linspace(-5, 5, 11))
# 调整y轴刻度
plt.yticks(np.linspace(1, 6, 6))
# 给坐标轴加箭头
plt.arrow(0, 7, 0, 0, width=0.2, color="k", clip_on=False, head_width=0.2, head_length=0.2)
plt.arrow(7, 0, 0.01, 0, width=0.2, color="k", clip_on=False, head_width=0.2, head_length=0.2)
# 显示图例说明
plt.legend()
# 显示
plt.show()
三、散点图
# coding:utf8
import matplotlib.pyplot as plt
# 先获取一个图表
fig = plt.figure()
# 设置x,y坐标轴的刻度显示范围
plt.xlim(-5, 20)
plt.ylim(-5, 30)
# 画散点图
X1 = [0, 10]
Y1 = [10, 20]
# c即color , s即scale
plt.scatter(X1, Y1, c='r', s=80, label='scatter 1')
plt.scatter([10, 15], [5, 10], c='g', label='scatter 2')
# 显示网格
plt.grid(True, alpha=0.3)
# 加上坐标说明
plt.text(0.5, 10.5, r'$(0,10)$')
plt.text(10.5, 20.5, r'$(10,20)$')
plt.text(10.5, 5.5, r'$(10,5)$')
plt.text(15.5, 10.5, r'$(15,10)$')
# 显示图例说明
plt.legend()
# 显示
plt.show()
参考文章:
6、莫烦的视频
作者:菩提树下的杨过
出处:http://yjmyzz.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://yjmyzz.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。