坐标变换与注释

4大坐标系
数据坐标系:x轴范围,y轴范围
子图坐标系:描述子图中位置的坐标系,左下角为(0,0),右上角为(1,1)
图表坐标系: 左下角为(0,0),右上角为(1,1)
窗口坐标系:左下角坐标为(0,0),右上角坐标为(width,height)
—————-为以像素为单位的坐标系,不包含标题栏、工具条及状态栏部分
axes对象:transData为数据坐标变换对象
————–transAxes为子图坐标变换对象
Figure对象:transFigure为图表变换对象

注释
在python模板中提供的绘制文字的函数为text()和figtext().
text():调用当前Axes对象的text()方法进行绘图,默认在数据坐标系中添加文字
figtext():调用当前figure对象的text()方法进行绘图,默认在图表坐标系中添加文字
可通过transform参数改变文字所在的坐标系。

通过pyplot模板的annotate()绘制带箭头的注释文字:
annotate(s,xy,xytext,xycoords=’data’,textcoords=’data’,arrowprops=None,…)
说明:s为注释文本,xy为箭头所指处的坐标,xytext为注释文本所处的坐标

# -*- coding: utf-8 -*-
import numpy
import matplotlib
import matplotlib.pyplot as plt 
from matplotlib import transforms
import numpy
import matplotlib.pyplot as plt
#直线
def func1(x):
    return 0.6*x+0.3
#曲线
def func2(x):
    return 0.4*x*x+0.1*x+0.2
#交点横坐标
def find_intersects(x,y1,y2):
    d=y1-y2
    idx=numpy.where(d[:-1]*d[1:]<=0)[0]
    x1,x2=x[idx],x[idx+1]
    d1,d2=d[idx],d[idx+1]
    return -d1*(x2-x1)/(d2-d1)+x1
#绘图
x=numpy.linspace(-3,3,100)
f1=func1(x)
f2=func2(x)
fig,ax=plt.subplots(figsize=(8,4))
ax.plot(x,func1(x),x,func2(x))

#找到交点横坐标,将交点用圆圈表示
x1,x2=find_intersects(x,f1,f2)
ax.plot(x1,func1(x1),'o')
ax.plot(x2,func2(x2),'o')

#直线>曲线部分的面积填充
ax.fill_between(x,f1,f2,where=f1>f2,color='g',alpha=0.5)

#将一个以数据横坐标为宽,子图高度为高的矩形,用颜色填充
#transforms的blended_transform_factory函数可创建一个混合坐标(数据坐标,子图坐标)
from matplotlib import transforms
trans=transforms.blended_transform_factory(ax.transData,ax.transAxes)
ax.fill_between([x1,x2],0,1,transform=trans,alpha=0.1)

#子图注释
a=ax.text(0.05,0.95,'直线与二次曲线的交点',transform=ax.transAxes,
          va='top',fontsize=18,
          bbox={'color':'r','alpha':0.4,})
#箭头注释
#data表示使用的是数据坐标系中的坐标变换对象
#axes fraction表示使用的是子图坐标系的坐标变换对象
#offset points表示文字与箭头的相对位置保持不变
#arrowprops为描述箭头样式的字典
arrow={'arrowstyle':'fancy,tail_width=0.6','color':'gray'}
ax.annotate('交点',xy=(x1,func1(x1)),xycoords='data',xytext=(0.4,0.5),
            textcoords='axes fraction',arrowprops=arrow)
ax.annotate('交点',xy=(x2,func2(x2)),xycoords='data',xytext=(0.4,0.5),
            textcoords='axes fraction',arrowprops=arrow)
xm=(x1+x2)/2
ym=(func1(xm)-func2(xm))/2+func2(xm)
ax.annotate('直线大于曲线区域',xy=(xm,ym),xycoords='data',xytext=(30,-30),
            textcoords='offset points',arrowprops=arrow,
            bbox={'color':'g','alpha':0.4,}
            )

这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_41357131/article/details/80151694