亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 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 關注
  • 144 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號