matplotlib画图
声明:本文章为个人学习"莫烦python"的视频课程笔记,课程链接如下:
莫烦个人教学网站
莫烦B站视频课程
import matplotlib.pylpot as plt
plt.figure()
plot(x,y,color = 'red',linewidth = 1.0, linestyle = '--')
plot.xlim((-1,2))
plot.ylim((-2,3))
plt.xlabel('I am x')
plt.ylabel('I am y')
new_ticks = np.linspace(-1,2,5) # 设置x轴间距
print(new_ticks)
plt.xticks(new_ticks) # x轴更换间距
# y 轴替换为字符
plt.yticks([-2, -1.8,-1,1.22,3],
['really good','bad','normal','good','really good']
# 统一字体 [r'$really\ good$',r'$bad$',r'$normal$',r'$good$',r'$really\ good$']
# 数学阿尔法 [r‘$\alpha$’]
# 画出四个象限的图
# gca = 'get current axis'
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',-1)) # x 轴绑定在y轴-1(normal)的位置处
ax.spines['left'].set_position(('data',0)) # y轴绑定在x轴0的位置处
# 图例
l1, = plt.plot(x,y1,label = 'up')
l2, = plt.plot(x,y2,label = 'down')
plt.legend() # 添加图例 不用l1,l2
plt.legend(handles = [l1,l2] , labels =['aaa','bbb'] , loc = 'best',)
# local:
"""
best
upper right
upper left
lower left
lower right
right
center left
center right
lower center
upper center
center
"""
常用设置:
- 设置线属性:使用 fmt 参数更改color, marker,line ; fmt=‘[color][marker][line]’
eg: plt.plot(predict, ‘mo-’, label=‘predict’,linewidth=5)
color:
character | ‘b’ | ‘g’ | ‘r’ | ‘c’ | ‘m’ | ‘y’ | ‘k’ | ‘w’ |
---|---|---|---|---|---|---|---|---|
color | blue | green | red | cyan | magenta | yellow | black | white |
markers:
linestyle:
1 添加注解
# 添加注解(例如强调某一个点)
x0 = 1
y0 = 2*x0 +1
plt.scatter(x0,y0, s=50. c0lor='b') # 散点图 size = 50
plt.plot([x0,x0],[y0.0],'k--',lw = 2.5) #