import numpy as np
import matplotlib.pyplot as plt
# 线性图
x = np.linspace(-5,5,100)
y1 = x * 2 + 3
y2 = (x ** 2) / 2
plt.figure(num=1,figsize=(8,5))
# plot绘制线条
l1 = plt.plot(x,y1,label='line',linestyle='--')
l2 = plt.plot(x,y2,label='curve',linewidth=5.0,alpha=0.5)
# xlim,ylim限制x,y轴显示范围
plt.xlim((-3,3))
plt.ylim((-5,10))
# xlabel,ylabel x,y轴名称
plt.xlabel('x')
plt.ylabel('y')
# legend显示标框
plt.legend(loc='best')
# 移动x,y轴位置
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',-1))
# xticks,yticks重定义坐标轴数据
# new_ticks = np.linspace(-3,3,7)
plt.xticks([-3,-2,-1,0,1,2,3],
[-2,-1,0,1,2,3,4])
# annotion注释
x0 = 1
y0 = x0 * 2 + 3
# 散点图
plt.scatter(x0,y0,s=50,color='b')
plt.plot([x0,x0],[y0,0],'k--',lw=2.5)
# method1
plt.annotate(r'$2x+3=%s$' % y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30),
textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.2"))
# 散点图
# 0-平均值,1-方差,n个呈标准正态分布的数组
n = 1024
X = np.random.normal(0.25,1.5,n)
Y = np.random.normal(0.25,1.5,n)
C = np.arctan2(Y,X) # 颜色值
plt.figure(num=2,figsize=(8,5))
plt.scatter(X,Y,s=50,alpha=0.7,c=C)
plt.xticks(())
plt.yticks(())
# 柱状图
# n,柱状图数量
n = 8
X = np.arange(n)
Y1 = 2*X + 3
Y2 = -Y1
plt.figure(num=3,figsize=(8,5))
plt.bar(X,Y1,facecolor='#99ffff',edgecolor='white')
plt.bar(X,Y2,facecolor='#ffff99',edgecolor='white')
# 在bar上显示文本,ha横向居中对齐,va纵向底部/顶部对齐
for x,y in zip(X,Y1):
plt.text(x,y+0.05,'%.2f'%y,ha='center',va='bottom')
for x,y in zip(X,Y2):
plt.text(x,y-0.05,'%.2f'%y,ha='center',va='top')
plt.show()
matplot线性图,散点图,柱状图的常用操作学习笔记
最新推荐文章于 2024-06-12 19:58:14 发布