gpt4 book ai didi

Python matplotlib,获取xtick标签的位置

转载 作者:行者123 更新时间:2023-11-28 21:42:12 24 4
gpt4 key购买 nike

如何获取 xtick 主要标签的位置?我从 label.get_position() 获得的值没有意义。

import numpy as np
import matplotlib.pyplot as plt

def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)

t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)

# fig, ax = plt.figure(1)
fig, ax = plt.subplots()
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')

# plt.show()
print(fig)
print(ax.get_position())

# ------------------------------------------------
# positions of the tick labels, incorrect (0,0) returned
# ------------------------------------------------
print([text.get_position() for text in ax.get_xticklabels()])
# correct tick label values
print(ax.get_xticks())

以上代码的输出是:

Figure(640x480)
Bbox('array([[ 0.125, 0.1 ],\n [ 0.9 , 0.9 ]])')
[(0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.0, 0.0)] <-- incorrect positions
[ 0. 1. 2. 3. 4. 5.]

如何获取 xtick 主要标签的位置?我从 label.get_position() 获得的值没有意义。有没有我不知道的转换?最终,我希望文本框的位置以 (x,y) 图像像素为单位。

最佳答案

如果你需要像素坐标,你需要图形坐标,并转换它们。

如果您需要有关转换的更多信息,请查看有关 matplotlib 转换的教程:ref

编辑:为了完整起见,我添加了指定 dpi 的选项,这将影响您的图形尺寸

import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt

def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)

t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)

# set the dpi you want in your final figure
dpi = 300
mpl.rcParams['figure.dpi'] = dpi

fig, ax = plt.subplots()
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')

# saving the figure: don't forget the dpi option!
fig.savefig('./out.png', format='png', dpi=dpi)

xtickslocs = ax.get_xticks()
ymin, _ = ax.get_ylim()
print('xticks pixel coordinates')
print(ax.transData.transform([(xtick, ymin) for xtick in xtickslocs]))
print('label bounding boxes')
print([l.get_window_extent() for l in ax.get_xticklabels()])

输出:

xticks pixel coordinates
array([[ 60. , 40. ],
[ 134.4, 40. ],
[ 208.8, 40. ],
[ 283.2, 40. ],
[ 357.6, 40. ],
[ 432. , 40. ]])
label bounding boxes
[Bbox([[56.4375, 25.5555555556], [63.5625, 35.5555555556]]),
Bbox([[130.8375, 25.5555555556], [137.9625, 35.5555555556]]),
Bbox([[205.2375, 25.5555555556], [212.3625, 35.5555555556]]),
Bbox([[279.6375, 25.5555555556], [286.7625, 35.5555555556]]),
Bbox([[354.0375, 25.5555555556], [361.1625, 35.5555555556]]),
Bbox([[428.4375, 25.5555555556], [435.5625, 35.5555555556]])]

关于Python matplotlib,获取xtick标签的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44012436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com