欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

matplotlib入门(一)

程序员文章站 2022-03-01 21:03:45
...

基本用法

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3,3,50)
y1=2*x+1
y2=x**2
plt.plot(x,y1)

plt.show()

figure图像

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3,3,50)
y1=2*x+1
y2=x**2
plt.figure()
plt.plot(x,y1)

plt.figure()
plt.plot(x,y2)

plt.show()

plt.figure()默认自动从1开始编号。括号中可以自行设置参数:eg(num=3,figsize(8,5))

设置坐标轴

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3,3,50)
y1=2*x+1
y2=x**2
#plt.figure()
#plt.plot(x,y1)

plt.figure(num=3,figsize=(8,5))
plt.plot(x,y2)
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
#坐标轴范围
plt.xlim((-1,2))
plt.ylim((-2,3))
#修改文字描述
plt.xlabel('I am x')
plt.ylabel('I am y')
#修改标尺
new_ticks = np.linspace(-1,2,6)
print(new_ticks)
plt.xticks(new_ticks)
plt.yticks([-2,-1.8,-1,1.22,3],
           [r'$really\ bad$',r'$bad\ \alpha$',r'$normal$',r'$good$','$really\ good$'])
plt.show()
#修改坐标轴位置
#spines:脊柱,指坐标轴四条边框。
#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',0)) #outward,axes
ax.spines['left'].set_position(('data',2))

legend图例

l1,=plt.plot(x,y2,label='up')
l2,=plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--',label='down')
plt.legend(handles=[l1,],labels=['aaa',],loc='best')

Annotation标注

x0 = 1
y0 = 2*x0+1
plt.scatter(x0,y0,s=50,color='b') #散点
plt.plot([x0,x0],[y0,0],'k--',lw=2.5) #k:black --:style

plt.show()

tick能见度

import matplotlib.pyplot as plt
import numpy as np

x=np.linspace(-3,3,50)
y=0.1*x
plt.plot(x,y,linewidth=10)
plt.ylim(-2,2)

#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',0)) #outward,axes
ax.spines['left'].set_position(('data',2))

for label in ax.get_xticklabels()+ax.get_yticklabels():
    label.set_fontsize(12)
    label.set_bbox(dict(facecolor='white',edgecolor='None',alpha=0.2))

plt.show()