使用 ax.text、matplotlib 相对于轴定位字体
Position font relative to axis using ax.text, matplotlib
我不确定如何使用 matplotlib 相对于轴对象正确定位字体。
示例:
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(10, 4), dpi=100)
x = [1, 2]
y = [3, 4]
y_loc = 4.1
x_loc = 0.95
fs = 12
ax = axes[0]
ax.plot(x, y)
_ = ax.text(x=x_loc, y=y_loc, s="Plot 1", fontsize=fs)
ax = axes[1]
ax.plot(x, y)
_ = ax.text(x=x_loc, y=y_loc, s="Plot 2", fontsize=fs)
ax = axes[2]
_ = ax.plot(x, y)
_ = ax.text(x=x_loc, y=y_loc, s="Plot 3", fontsize=fs)
给出:
使用值:
y_loc = 4.1
x_loc = 0.95
让我觉得应该有更好的方法来解决这个问题。
注意 - 我想在这里使用 ax.text
,而不是 title
,问题主要是关于如何最好地定位文本相对于子图中特定轴的位置。理想情况下,如果它只是相对于特定轴,它也会扩展到网格图。
默认,ax.text
uses "data coordinates", i.e. with x and y as shown on the ticks of the axes. To plot relative to the rectangle defined by the axes, use transform=ax.transAxes
. Here 0,0
will be the point at the bottom left and 1,1
the point at the top right. (This kind of coordinates is also very useful when positioning a legend。)
from matplotlib import pyplot as plt
import numpy as np
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(10, 4), dpi=100)
for ind, ax in enumerate(axes):
ax.plot(np.random.randint(0, 10, 2), np.random.randint(0, 10, 2))
ax.text(x=0, y=1.05, s=f"Plot {ind+1}", fontsize=12, transform=ax.transAxes)
plt.show()
我不确定如何使用 matplotlib 相对于轴对象正确定位字体。
示例:
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(10, 4), dpi=100)
x = [1, 2]
y = [3, 4]
y_loc = 4.1
x_loc = 0.95
fs = 12
ax = axes[0]
ax.plot(x, y)
_ = ax.text(x=x_loc, y=y_loc, s="Plot 1", fontsize=fs)
ax = axes[1]
ax.plot(x, y)
_ = ax.text(x=x_loc, y=y_loc, s="Plot 2", fontsize=fs)
ax = axes[2]
_ = ax.plot(x, y)
_ = ax.text(x=x_loc, y=y_loc, s="Plot 3", fontsize=fs)
给出:
使用值:
y_loc = 4.1
x_loc = 0.95
让我觉得应该有更好的方法来解决这个问题。
注意 - 我想在这里使用 ax.text
,而不是 title
,问题主要是关于如何最好地定位文本相对于子图中特定轴的位置。理想情况下,如果它只是相对于特定轴,它也会扩展到网格图。
默认,ax.text
uses "data coordinates", i.e. with x and y as shown on the ticks of the axes. To plot relative to the rectangle defined by the axes, use transform=ax.transAxes
. Here 0,0
will be the point at the bottom left and 1,1
the point at the top right. (This kind of coordinates is also very useful when positioning a legend。)
from matplotlib import pyplot as plt
import numpy as np
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(10, 4), dpi=100)
for ind, ax in enumerate(axes):
ax.plot(np.random.randint(0, 10, 2), np.random.randint(0, 10, 2))
ax.text(x=0, y=1.05, s=f"Plot {ind+1}", fontsize=12, transform=ax.transAxes)
plt.show()