在matplotlib7中说明了,除了描述箭头属性的参数,其余传入annotate函数的参数,都将解释为text的属性参数。

1. text的bbox属性 以及其他的属性

描述Text的属性,包括颜色,字体大小,字体类型等
matplotlib.text.Text

着重讲述一下字典属性bbox
简单的说就是在用不同的矩形框将文字框起来,并用一系列属性来定义矩形框的

  • boxstyle : 矩形框的类型
  • alpha: [0, 1] 透明度,0为完全透明,1为完全不透明
import numpy.random
import matplotlib.pyplot as pltfig = plt.figure(1, figsize=(5,5))
fig.clf()ax = fig.add_subplot(111)
ax.set_aspect(1)x1 = -1 + numpy.random.randn(100)
y1 = -1 + numpy.random.randn(100)
x2 = 1. + numpy.random.randn(100)
y2 = 1. + numpy.random.randn(100)ax.scatter(x1, y1, color="r")
ax.scatter(x2, y2, color="g")# 设置Sample A/B的bbox
bbox_props = dict(boxstyle="round", fc="w", ec="0.5", alpha=0.9)
ax.text(-2, -2, "Sample A", ha="center", va="center", size=20,bbox=bbox_props)
ax.text(2, 2, "Sample B", ha="center", va="center", size=20,bbox=bbox_props)# 设置Direction Text的bbox
bbox_props = dict(boxstyle="rarrow", fc=(0.8,0.9,0.9), ec="b", lw=2)
t = ax.text(0, 0, "Direction", ha="center", va="center", rotation=45,size=15,bbox=bbox_props)# 通过text对象的get_bbox_patch方法可以得到bbox对象,利用set_*方法设置属性
bb = t.get_bbox_patch()
bb.set_boxstyle("rarrow", pad=0.6)ax.set_xlim(-4, 4)
ax.set_ylim(-4, 4)plt.draw()
plt.show()

  1. 在matplotlib7中有一张图,可以看出tick的label看不清楚了,通过label中的set_*方法可以对字体以及透明度重新设置
import matplotlib.pyplot as plt
import numpy as npx = np.linspace(-np.pi, np.pi, 128,endpoint=True)
cosx,sinx,x_3 = np.cos(x), np.sin(x), x / 3#%%
fig = plt.figure(1)
axes0 = plt.subplot(111)
line1, line2 = axes0.plot(x, cosx, 'r',x, sinx, 'c')line1.set_linewidth(2.5)
line2.set_linewidth(1)
# plt.xlim(x.min() *2, x.max()*2)
axes0.set_xlim(x.min() *1.2, x.max()*1.2)
axes0.set_ylim(cosx.min() * 1.2, cosx.max() * 1.2)axes0.set_xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi])
axes0.set_xticklabels([r'$-\pi$', r'$-\frac{\pi}{2}$', 0,  r'$+\frac{\pi}{2}$', r'$+\pi$'])
axes0.set_yticks([-1, 0, 1])
axes0.set_yticklabels([r'-1', r'0', r'+1'])# add legend
axes0.legend([line1, line2], ['y=cos(x)', 'y=sin(x)'])# 轴居中
axes0.spines['right'].set_color('none')
axes0.spines['top'].set_color('none')
axes0.xaxis.set_ticks_position('bottom')
axes0.spines['bottom'].set_position(('data',0))
axes0.yaxis.set_ticks_position('left')
axes0.spines['left'].set_position(('data',0))
# 添加注释
t = 2 * np.pi / 3# 通过添加散点来是的图更好看[t,0], [t, 0.01],  ....[t, np.sin(t)]
axes0.plot([t, t], [0, np.sin(t)], color='c', linewidth=1.5, linestyle="--")
axes0.scatter([t],[np.sin(t)] ,s=50, c='c')
axes0.annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',xy=(t, np.sin(t)), xycoords='data',xytext=(+10, +30), textcoords='offset points',fontsize=16, color= 'c',arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))# 同样对cosx做处理
axes0.plot([t, t], [0, np.cos(t)], color='r', linewidth=1.5, linestyle="--")
axes0.scatter([t],[np.cos(t)] ,s=50, c='r')
axes0.annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$',xy=(t, np.cos(t)), xycoords='data',xytext=(-90, -50), textcoords='offset points',fontsize=16, color= 'r',arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))# newly code added
for label in axes0.get_xticklabels() + axes0.get_yticklabels():label.set_fontsize(16)label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.9 ))plt.show()

2. 设置箭头属性

  • arrowprops 字典属性

箭头创建过程如下:

import matplotlib.pyplot as plt
import matplotlib.patches as mpatchesx1, y1 = 0.3, 0.3
x2, y2 = 0.7, 0.7fig = plt.figure(1, figsize=(8,3))from mpl_toolkits.axes_grid.axes_grid import AxesGrid
from mpl_toolkits.axes_grid.anchored_artists import AnchoredText#from matplotlib.font_manager import FontPropertiesdef add_at(ax, t, loc=2):fp = dict(size=10)_at = AnchoredText(t, loc=loc, prop=fp)ax.add_artist(_at)return _atgrid = AxesGrid(fig, 111, (1, 4), label_mode="1", share_all=True)grid[0].set_autoscale_on(False)ax = grid[0]
ax.plot([x1, x2], [y1, y2], ".")
el = mpatches.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.2)
ax.add_artist(el)
'''
add code to plot arrow
'''plt.draw()
plt.show()

接下来只贴创建过程中的参数代码

  1. 在两点之间创建一条连接路径,通过参数connectionstyle控制
ax.annotate("",xy=(x1, y1), xycoords='data',xytext=(x2, y2), textcoords='data',arrowprops=dict(arrowstyle="-", #linestyle="dashed",color="0.5",patchB=None,shrinkB=0,connectionstyle="arc3,rad=0.3",),)add_at(ax, "connect", loc=2)

  1. 如果给出patch对象(patchA或patchB),路径会省略掉一部分防止与patch对象交叠
ax.annotate("",xy=(x1, y1), xycoords='data',xytext=(x2, y2), textcoords='data',arrowprops=dict(arrowstyle="-", #linestyle="dashed",color="0.5",patchB=None,shrinkB=0,connectionstyle="arc3,rad=0.3",),)add_at(ax, "connect", loc=2)

  1. 接下通过shrinkA,shrinkB参数确定与patch边缘的距离
ax.annotate("",xy=(x1, y1), xycoords='data',xytext=(x2, y2), textcoords='data',arrowprops=dict(arrowstyle="-", #linestyle="dashed",color="0.5",patchB=el,shrinkB=5,connectionstyle="arc3,rad=0.3",),)add_at(ax, "shrink", loc=2)

  1. 最后通过arrowstyle参数确定arrow的形状
ax.annotate("",xy=(x1, y1), xycoords='data',xytext=(x2, y2), textcoords='data',arrowprops=dict(arrowstyle="fancy", #linestyle="dashed",color="0.5",patchB=el,shrinkB=5,connectionstyle="arc3,rad=0.3",),)add_at(ax, "mutate", loc=2)

关于connectionstyle,
示例代码以及图片:


import matplotlib.pyplot as plt
import matplotlib.patches as mpatchesfig = plt.figure(1, figsize=(8,5))
fig.clf()
from mpl_toolkits.axes_grid.axes_grid import AxesGrid
from mpl_toolkits.axes_grid.anchored_artists import AnchoredText#from matplotlib.font_manager import FontPropertiesdef add_at(ax, t, loc=2):fp = dict(size=8)_at = AnchoredText(t, loc=loc, prop=fp)ax.add_artist(_at)return _atgrid = AxesGrid(fig, 111, (3, 5), label_mode="1", share_all=True)grid[0].set_autoscale_on(False)x1, y1 = 0.3, 0.3
x2, y2 = 0.7, 0.7def demo_con_style(ax, connectionstyle, label=None):if label is None:label = connectionstylex1, y1 = 0.3, 0.2x2, y2 = 0.8, 0.6ax.plot([x1, x2], [y1, y2], ".")ax.annotate("",xy=(x1, y1), xycoords='data',xytext=(x2, y2), textcoords='data',arrowprops=dict(arrowstyle="->", #linestyle="dashed",color="0.5",shrinkA=5, shrinkB=5,patchA=None,patchB=None,connectionstyle=connectionstyle,),)add_at(ax, label, loc=2)column = grid.axes_column[0]demo_con_style(column[0], "angle3,angleA=90,angleB=0",label="angle3,\nangleA=90,\nangleB=0")
demo_con_style(column[1], "angle3,angleA=0,angleB=90",label="angle3,\nangleA=0,\nangleB=90")column = grid.axes_column[1]demo_con_style(column[0], "arc3,rad=0.")
demo_con_style(column[1], "arc3,rad=0.3")
demo_con_style(column[2], "arc3,rad=-0.3")column = grid.axes_column[2]demo_con_style(column[0], "angle,angleA=-90,angleB=180,rad=0",label="angle,\nangleA=-90,\nangleB=180,\nrad=0")
demo_con_style(column[1], "angle,angleA=-90,angleB=180,rad=5",label="angle,\nangleA=-90,\nangleB=180,\nrad=5")
demo_con_style(column[2], "angle,angleA=-90,angleB=10,rad=5",label="angle,\nangleA=-90,\nangleB=10,\nrad=0")column = grid.axes_column[3]demo_con_style(column[0], "arc,angleA=-90,angleB=0,armA=30,armB=30,rad=0",label="arc,\nangleA=-90,\nangleB=0,\narmA=30,\narmB=30,\nrad=0")
demo_con_style(column[1], "arc,angleA=-90,angleB=0,armA=30,armB=30,rad=5",label="arc,\nangleA=-90,\nangleB=0,\narmA=30,\narmB=30,\nrad=5")
demo_con_style(column[2], "arc,angleA=-90,angleB=0,armA=0,armB=40,rad=0",label="arc,\nangleA=-90,\nangleB=0,\narmA=0,\narmB=40,\nrad=0")column = grid.axes_column[4]demo_con_style(column[0], "bar,fraction=0.3",label="bar,\nfraction=0.3")
demo_con_style(column[1], "bar,fraction=-0.3",label="bar,\nfraction=-0.3")
demo_con_style(column[2], "bar,angle=180,fraction=-0.2",label="bar,\nangle=180,\nfraction=-0.2")#demo_con_style(column[1], "arc3,rad=0.3")
#demo_con_style(column[2], "arc3,rad=-0.3")grid[0].set_xlim(0, 1)
grid[0].set_ylim(0, 1)
grid.axes_llc.axis["bottom"].toggle(ticklabels=False)
grid.axes_llc.axis["left"].toggle(ticklabels=False)
fig.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95)plt.draw()
plt.show()

关于arrowstyle

import matplotlib.patches as mpatches
import matplotlib.pyplot as pltstyles = mpatches.ArrowStyle.get_styles()ncol = 2
nrow = (len(styles) + 1) // ncol
figheight = (nrow + 0.5)
fig1 = plt.figure(1, (4.*ncol/1.5, figheight/1.5))
fontsize = 0.2 * 70ax = fig1.add_axes([0, 0, 1, 1], frameon=False, aspect=1.)ax.set_xlim(0, 4*ncol)
ax.set_ylim(0, figheight)def to_texstring(s):s = s.replace("<", r"$<$")s = s.replace(">", r"$>$")s = s.replace("|", r"$|$")return sfor i, (stylename, styleclass) in enumerate(sorted(styles.items())):x = 3.2 + (i//nrow)*4y = (figheight - 0.7 - i % nrow)  # /figheightp = mpatches.Circle((x, y), 0.2)ax.add_patch(p)ax.annotate(to_texstring(stylename), (x, y),(x - 1.2, y),#xycoords="figure fraction", textcoords="figure fraction",ha="right", va="center",size=fontsize,arrowprops=dict(arrowstyle=stylename,patchB=p,shrinkA=5,shrinkB=5,fc="k", ec="k",connectionstyle="arc3,rad=-0.05",),bbox=dict(boxstyle="square", fc="w"))ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)plt.draw()
plt.show()

示例代码:

fig = plt.figure(1)
ax = fig.subplots()
line1,  = ax.plot(x, cosx, 'c-.',label = 'y=cos(x)' )ax.set_xlim(x.min() *1.2, x.max()*1.2)
ax.set_ylim(cosx.min() * 1.2, cosx.max() * 1.2)
t =  np.pi / 3# 注释[t, np.cos(t)]
ax.scatter([t], [np.cos(t)], s=30, c='r')
ax.plot([t, t], [cosx.min() * 1.2, np.cos(t)], color='r', linewidth=1.5, linestyle="--")ax.annotate(r'$\cos(\frac{\pi}{3})=\frac{1}{2}$',xy=(t, np.cos(t)), xycoords='data',xytext=(+30, +40), textcoords='offset points',fontsize=16, color= 'r',# bboxbbox=dict(boxstyle="round4", fc="w"),# arrowarrowprops=dict(arrowstyle="-|>", connectionstyle="angle,angleA=-90,angleB=180,rad=0"))plt.show()

matplotlib8 -- 文字注释进一步详解 bbox参数, 箭头形状等相关推荐

  1. yolov5——detect.py代码【注释、详解、使用教程】

    yolov5--detect.py代码[注释.详解.使用教程] yolov5--detect.py代码[注释.详解.使用教程] 1. 函数parse_opt() 2. 函数main() 3. 函数ru ...

  2. java 注释 超链接_java_Java代码注释规范详解,代码附有注释对程序开发者来 - phpStudy...

    Java代码注释规范详解 代码附有注释对程序开发者来说非常重要,随着技术的发展,在项目开发过程中,必须要求程序员写好代码注释,这样有利于代码后续的编写和使用. 基本的要求: 1.注释形式统一 在整个应 ...

  3. java文档注释定界符_c语言的注释定界符详解

    c语言的注释定界符详解 c语言的注释定界符是什么 1.最早期的C语言注释是:/* */ 2.后来又增加的行注释:// 其中/**/是多行注释,//是单行注释. 需要注意的是:C 语言的注释并不是可以出 ...

  4. 【Vue路由(router)进一步详解】

    Vue路由(router)进一步详解 query属性 具体实例代码如下: params属性 具体实例代码如下: props属性 replace属性 编程式路由导航 路由缓存 具体代码: 总结 本篇文章 ...

  5. yolov5——train.py代码【注释、详解、使用教程】

    yolov5--train.py代码[注释.详解.使用教程] yolov5--train.py代码[注释.详解.使用教程] yolov5--train.py代码[注释.详解.使用教程] 前言 1. p ...

  6. 线程池源代码详解,参数详解

    线程池源代码详解,参数详解 ThreadPoolExecutor 构造函数源代码 public ThreadPoolExecutor(int corePoolSize, int maximumPool ...

  7. python bytearray转为byte_Python3 bytearray() 函数详解 将参数转为可变的字节数组

    Python3 bytearray() 函数详解 将参数转为可变的字节数组 bytearray()函数的主要用途是将参数转换为一个新的字节数组,它是一个可变的整数序列,它的取值范围是0 <= x ...

  8. python bytes 改值_Python3 bytes() 函数详解 将参数转为不可变的字节数组

    Python3 bytes() 函数详解 将参数转为不可变的字节数组 bytes()函数的主要用途是将参数转换为一个新的字节数组,它是一个不可变的整数序列,它的取值范围是0 <= x < ...

  9. ioctl函数详解(参数详解,驱动unlocked_ioctl使用、命令码如何封装)

    @ioctl函数详解 一.ioctl函数的原型 在用户空间的函数原型 #include <sys/ioctl.h> int ioctl(int d, int request, ...); ...

最新文章

  1. mongodb 结果二次调用_mongodb慢查询记录
  2. python 学习笔记(3)-转载
  3. java生成验证码工具类_Java生成图形验证码工具类
  4. Warning: mysqli_connect()_php链接MySQL8.0_异常
  5. 18行代码AC_Wet Shark and Bishops CodeForces - 621B(数学推导+映射)
  6. Jq remove的使用
  7. 字节前端终于开源!吹爆!
  8. mysql 中 group_concat()用法
  9. 笑跪!博士写论文解释科学擀面,学霸们每天都在想些啥…
  10. 前端_网页编程 跨域与JSONP- 淘宝搜索案例
  11. ubuntu中显示本机的gpu_Ubuntu下实时查看Nvidia显卡显存占用情况和GPU温度
  12. Apache服务器 403 Forbidden的几种错误原因小结!
  13. perl删除文件_Perl小知识语法重点和数据类型
  14. laravel连接oracle6,Laravel 使用 Oracle 数据库
  15. Bailian2743 字符串判等【字符串】
  16. linux gpio-led
  17. Matlab矩阵的运算
  18. 沙盘模拟软件_我院学生参加第十六届全国大学生“新道杯”沙盘模拟经营大赛喜获佳绩...
  19. 西门子PLC编程软件step7 v5.5 和仿真软件S7-Plcsim安装与授权
  20. qtcpsocket断开_关于使用QTcpSocket的一些总结

热门文章

  1. 大数据存储项目-基于Flink的高速公路ETC入深圳数据实时分析平台
  2. 上海怎样盘活闲置房 区县:多种方式支持
  3. 快手坐拥3亿用户,想成为平行世界里的Snapchat,然后呢
  4. 【windows】win8.1的安装中绕过Microsoft帐户登录
  5. FileUpload文件上传
  6. Neo4j图数据库从入门到精通
  7. 因式分解机(Factorization Machines,FM )
  8. consistent equation
  9. 宽带的服务器未响应,宽带拨号服务器未响应
  10. 【WCN685X】WCN6856 5G吞吐量测试只有25Mbps问题原因分析及解决方案