matplotlib是受MATLAB启发而诞生的,其绘图方式类似于MATLAB
一般来说,绘图的大部分功能都可以通过matplotlib.pyplot实现,对于notebook,需要打开魔法开关%matplotlib inline,图像才会在浏览器中显示
绘图基础
#matplotlib绘图
import numpy as np
#标识图像绘制在notebook中
%matplotlib inline
import matplotlib.pyplot as plt
#用于处理中文
plt.rcParams['font.sans-serif']=['SimHei']#用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
绘图首先要确定画板,然后对画板分割区域,将图形绘制到对应区域中,机器绘图总是离散的,如果点选择够密集,看起来就是连续的:
#设置画板大小
plt.figure(figsize=(10,6))
#把画板拆成1行1列,取第一个区域作图
plt.subplot(1,1,1)
#生产256个点
X=np.linspace(-np.pi,np.pi,256,endpoint=True)
#多元赋值
C,S=np.cos(X),np.sin(X)
#用宽度为1(像素)的蓝色连续直线绘制
plt.plot(X,C,color="blue",linewidth=1.0,linestyle="-")
#用宽度为1(像素)的绿色连续直线绘制
plt.plot(X,S,color="green",linewidth=1.0,linestyle="-")
#设置X轴的极值
plt.xlim(-4.0,4.0)
#设置X轴的刻度值
plt.xticks(np.linspace(-4,4,9,endpoint=True))
plt.ylim(-1.0,1.0)
plt.yticks(np.linspace(-1,1,5,endpoint=True))
#在屏幕上显示结果
plt.show()

上图看起来不符合数学的标准,我希望图形的坐标x,y轴在(0,0)相交,因此我需要移动坐标,两条曲线各代表什么也没有说明,因此,还需要添加图例:
#移动坐标轴和图例
ax=plt.gca()#get current axis:获取当前坐标系
#将该坐标系的右边缘和上边缘设为透明
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
#设置bottom是x轴
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
#设置left为y轴
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
#区间重新设置
plt.setp(ax,
xticks=[-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
xticklabels=[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])
plt.setp(ax,
yticks=[-1, 0, +1],
yticklabels=[r'$-1$', r'$0$', r'$+1$'])
#重新绘图
ax.plot(X, C, color="blue", linewidth=1.0, linestyle='-', label="cos")
ax.plot(X, S, color="green", linewidth=1.0, linestyle='-', label="sin")
#图例:位置左上角
ax.legend(loc='upper left') # 顺序要在plot后面
在xticklabels中有'$-\pi$'一类的字符串,这是latex的字符串渲染

对于一些场景,需要在图像中进行特殊点标注:
# 特殊点标注
t = 2 * np.pi / 3
"""
xy:标注位置
xycoords使用的坐标系,'data'为原始坐标系
xytext+textcoords='offset points':文本相对标注的位置
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")箭头的具体形状
"""
ax.annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',
xy=(t, np.sin(t)), xycoords='data',
xytext=(+10, +30), textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
ax.annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$',
xy=(t, np.cos(t)), xycoords='data',
xytext=(-90, -50), textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
#补作散点
ax.scatter([t,], [np.sin(t),], 50, color ='green')
ax.scatter([t,], [np.cos(t),], 50, color ='blue')
plt.show()

图像嵌套
ax=plt.gca()即get current axis:用于获取当前坐标系
# 图嵌套
x = np.linspace(0, 5, 10)
y = x ** 2
fig = plt.figure()
#在当前画板内加子画板
# axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1)
axes = fig.gca()
axes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3]) # inset axes
axes.plot(x, y, 'r')
axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title')
# insert
axes2.plot(y, x, 'g')
axes2.set_xlabel('y')
axes2.set_ylabel('x')
axes2.set_title('insert title');
plt.show()

柱状图
一维柱状图:
# 正态分布柱状图
mu =0.0
sigma = 2.0
samples = np.random.normal(loc=mu, scale=sigma, size=2000)
#(2000,) class np.ndarray
plt.figure(num=1, figsize=(8,6))
plt.title('Normal Distribution', size=10)
plt.xlabel('value', size=10)
plt.ylabel('counts', size=10)
plt.hist(samples, bins=80, range=(-10,10)) # bins=柱子数目

二维柱状图:
#x,y各自生成1000个标准正态分布
x = np.random.randn(1000)
y = np.random.randn(1000)
# 画图,bins:横竖分为几条
plt.hist2d(x=x, y=y, bins=30)
# 展示
plt.show()

雷达图
#雷达图:使用极坐标
def radar_plot():
"""
radar plot
"""
# 生成测试数据
labels = np.array(["A", "B", "C", "D", "E", "F"])
data = np.array([68, 83, 90, 77, 89, 73])
theta = np.linspace(0, 2*np.pi, len(data), endpoint=False)
# 数据预处理
data = np.concatenate((data, [data[0]]))
print(data)
theta = np.concatenate((theta, [theta[0]]))
# 画图方式
plt.subplot(111, polar=True)
plt.title("Radar")
# 设置"theta grid"/"radar grid"
plt.thetagrids(theta*(180/np.pi), labels=labels)
plt.rgrids(np.arange(20, 100, 20), labels=np.arange(20, 100, 20), angle=0)
plt.ylim(0, 100)
# 画雷达图,并填充雷达图内部区域
plt.plot(theta, data, "bo-", linewidth=2)
plt.fill(theta, data, color="red", alpha=0.25)
# 图形显示
plt.show()
return
radar_plot()

饼图
#饼图
def pie_plot():
"""
pie plot
"""
# 生成测试数据
sizes = [15.88, 29.12, 45, 10]
labels = ["Frogs", "Chinese", "Dogs", "Logs"]
colors = ["yellowgreen", "gold", "lightskyblue", "lightcoral"]
# 设置标题
plt.title("Pie")
# 设置突出参数:离圆心距离
explode = [0, 0.1, 0, 0]
# 画饼状图
patches, l_text, p_text = plt.pie(sizes,
explode=explode,
labels=labels,
colors=colors,
autopct="%.2f%%",
shadow=True,#阴影效果
startangle=180)#旋转方向
#让画板是正方形,从而饼图也是圆的
plt.axis("equal")
# 图形显示
plt.show()
return
pie_plot()

1649

被折叠的 条评论
为什么被折叠?



