基础应用
使用import导入模块matplotlib.pyplot
plt.figure() #创建一个窗口
plt.plot(x, y) #画上点
plt.show() #显示出来
figure图像:
plt.figure(num=3, figsize=(8, 5),)#编号为3,大小为8*5
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--') #线的颜色为red,宽度为1.0,线的样式--
设置坐标轴:
使用plt.xlim设置x坐标轴范围:(-1, 2);
使用plt.ylim设置y坐标轴范围:(-2, 3);
使用plt.xlabel设置x坐标轴名称:’I am x’;
使用plt.ylabel设置y坐标轴名称:’I am y’;
plt.xlim((-1, 2))
plt.ylim((-2, 3))
plt.xlabel('I am x')
plt.ylabel('I am y')
plt.xticks设置x轴刻度:
范围是(-1,2);个数是5.
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
使用plt.yticks设置y轴刻度以及名称:
刻度为[-2, -1.8, -1, 1.22, 3];对应刻度的名称为[‘really bad’,’bad’,’normal’,’good’, ‘really good’]
plt.yticks([-2, -1.8, -1, 1.22, 3],[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$']) #设置y的值,并起名字
使用plt.gca获取当前坐标轴信息.
使用.spines设置边框:右侧边框 ax.spines['right'];
使用.set_color设置边框颜色:默认白色;
使用.spines设置边框:上边框 ax.spines['top'];
使用.set_color设置边框颜色:默认白色;
ax.spines["right"].set_color("none") #右边框消失
ax.spines["top"].set_color("none") #上边框消
ax.xaxis.set_ticks_position("bottom") #x轴用下面的轴代替
ax.yaxis.set_ticks_position("left") #y轴用左边的轴代替
ax.spines["bottom"].set_position(("data",0)) #开始移动他的位置,data是数据点 0代表原点是0
ax.spines["left"].set_position(("data",0))
设置图例:
# set line label1
l1, = plt.plot(x, y1, label='linear line')
plt.plot(x,y,label="test")
plt.legend(loc='upper right') #loc='upper right' 表示图例将添加在图中的右上角
# set line label2
l1, = plt.plot(x, y1, label='linear line')
l2, = plt.plot(x, y1, label='linear line')
plt.legend(handles=[l1,l2], labels=['up', 'down'], loc='best') loc的内容查文档
需要注意的是 l1, l2,要以逗号结尾, 因为plt.plot() 返回的是一个列表
标注:
添加注释 annotate
plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30),
textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.2"))
其中参数xycoords='data' 是说基于数据的值来选位置,
xytext=(+30, -30) 和 textcoords='offset points' 对于标注位置的描述 和 xy 偏差值,
arrowprops是对图中箭头类型的一些设置.
添加注释 text
plt.text(-3.7, 3, r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',
fontdict={'size': 16, 'color': 'r'})
其中-3.7, 3,是选取text的位置, 空格需要用到转字符\ ,fontdict设置文本字体.
x,y标签能见度
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(12) #设置x,y标签的大小
# 在 plt 2.0.2 或更高的版本中, 设置 zorder 给 plot 在 z 轴方向排序
label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.7, zorder=2))
plt.show()
其中label.set_fontsize(12)重新调节字体大小,bbox设置目的内容的透明度相关参,facecolor调节 box 前景色,edgecolor 设置边框, 本处设置边框为无,alpha设置透明度。ax.get_xticklabels() + ax.get_yticklabels()#获取所有x,y的标签值
散点图:
scatter(x,y,s=50,c=,alpha=0.6) #---s散点的个数,c是散点的颜色,alpha透明度