为了账号安全,请及时绑定邮箱和手机立即绑定

使用 matplotlib 在对数刻度上居中注释

使用 matplotlib 在对数刻度上居中注释

神不在的星期二 2022-11-09 16:44:27
我有以下不言自明的情况;请参阅下面粘贴的图和工作示例。我想知道如何在尺寸线的中间居中文本。import numpy as npimport matplotlib.pyplot as plt# Dimension linedef annotation_line(ax, xmin, xmax, y, text, ytext=0, linecolor='black', linewidth=1, fontsize=12):    ax.annotate('', xy=(xmin, y), xytext=(xmax, y), xycoords='data', textcoords='data', arrowprops={'arrowstyle': '|-|', 'color':linecolor, 'linewidth':linewidth})    ax.annotate('', xy=(xmin, y), xytext=(xmax, y), xycoords='data', textcoords='data', arrowprops={'arrowstyle': '<->', 'color':linecolor, 'linewidth':linewidth})    xcenter = xmin + (xmax - xmin) / 2    if ytext==0:        ytext = y + ( ax.get_ylim()[1] - ax.get_ylim()[0] ) / 20    ax.annotate(text, xy=(xcenter, ytext), ha='center', va='bottom', fontsize=fontsize)# Toy dataN = 8y = np.zeros(N)x1 = np.linspace(1, 1000, N, endpoint=True)fig, ax = plt.subplots(figsize=(10, 6))ax.plot(x1, y, 'o')annotation_line(ax=ax, text='TEXT 1', xmin=1, xmax=100, y=0.01, ytext=0, linewidth=1, linecolor='gray', fontsize=12)ax.set_xscale('log')
查看完整描述

1 回答

?
www说

TA贡献1775条经验 获得超8个赞

简单的解决方案是按照@JohanC 的建议进行操作并计算对数坐标的中点。


另一种解决方案是使用箭头的坐标来找到它的中点。然而,这种方法也有缺点。首先,您需要在中间步骤显式绘制图形,因为坐标仅在绘制时有效,其次,您需要在绘制注释之前设置对数比例。另一方面,无论轴的缩放如何,代码都可以工作


import numpy as np

import matplotlib.pyplot as plt


# Dimension line

def annotation_line(ax, xmin, xmax, y, text, ytext=0, linecolor='black', linewidth=1, fontsize=12):

    an = ax.annotate('', xy=(xmin, y), xytext=(xmax, y), xycoords='data', textcoords='data', arrowprops={'arrowstyle': '|-|', 'color':linecolor, 'linewidth':linewidth})

    ax.annotate('', xy=(xmin, y), xytext=(xmax, y), xycoords='data', textcoords='data', arrowprops={'arrowstyle': '<->', 'color':linecolor, 'linewidth':linewidth})

    ax.figure.canvas.draw() # draw to get actual coordinates

    p = an.arrow_patch.get_path().transformed(ax.transAxes.inverted())

    xmin, xmax = np.min(p.vertices[:,0]),np.max(p.vertices[:,0])

    xcenter = xmin+(xmax-xmin)/2

    if ytext==0:

        ytext = y + ( ax.get_ylim()[1] - ax.get_ylim()[0] ) / 20

    ax.annotate(text, xy=(xcenter, ytext), xycoords=('axes fraction','data'), ha='center', va='bottom', fontsize=fontsize)

    return an


# Toy data

N = 8

y = np.zeros(N)

x1 = np.linspace(1, 1000, N, endpoint=True)


fig, ax = plt.subplots(figsize=(10, 6))

ax.plot(x1, y, 'o')

ax.set_xscale('log') # must do before the call to annotation_line

an = annotation_line(ax=ax, text='TEXT 1', xmin=1, xmax=100, y=0.01, ytext=0, linewidth=1, linecolor='gray', fontsize=12)



查看完整回答
反对 回复 2022-11-09
  • 1 回答
  • 0 关注
  • 164 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号