相对于绘图坐标设置 xticks
Set xticks relative to the plot coordinates
对于 x 轴上具有不同范围的两个图,是否有一种简单的方法可以将两个 xticks 设置为距 xmin 和 xmax 的距离相等?
# Example:
from matplotlib import pyplot as plt
import matplotlib.gridspec as gridspec
fig = plt.figure(figsize=(6,4), constrained_layout=True)
gs = gridspec.GridSpec(ncols=2, nrows=1, figure=fig)
x1 = [1, 0.6, 0.4, 0.3, 0.25, 0.24, 0.23]
x2 = [0.1, 0.14, 0.15, 0.16, 0.166, 0.1666, 0.1666 ]
y = [1, 2, 3, 4, 5, 6, 7]
# xticks
number_of_xticks = 2
# Plot 1:
ax0 = fig.add_subplot(gs[0, 0])
ax0.plot(x1, y)
ax0.xaxis.set_major_locator(plt.MaxNLocator(number_of_xticks))
# Plot 2:
ax1 = fig.add_subplot(gs[0, 1])
ax1.plot(x2, y)
ax1.xaxis.set_major_locator(plt.MaxNLocator(number_of_xticks))
plt.show()
示例代码不起作用,因为 xticks 与两个图中的 xmin 和 xmax 的距离不同:
您可以尝试指定沿 x 范围的相对距离:
# xticks
tick_fractions = [1/4, 3/4]
然后根据每个 x 范围计算刻度位置:
mini = min(x)
maxi = max(x)
dist = maxi - mini
ax.set_xticks([mini + f * dist for f in tick_fractions])
所以完整的脚本看起来像:
# Example:
from matplotlib import pyplot as plt
import matplotlib.gridspec as gridspec
fig = plt.figure(figsize=(6,4), constrained_layout=True)
gs = gridspec.GridSpec(ncols=2, nrows=1, figure=fig)
x1 = [1, 0.6, 0.4, 0.3, 0.25, 0.24, 0.23]
x2 = [0.1, 0.14, 0.15, 0.16, 0.166, 0.1666, 0.1666 ]
y = [1, 2, 3, 4, 5, 6, 7]
# xticks
tick_fractions = [1/4, 3/4]
# Plot 1:
ax0 = fig.add_subplot(gs[0, 0])
ax0.plot(x1, y)
mini = min(x1)
maxi = max(x1)
dist = maxi - mini
ax0.set_xticks([mini + f * dist for f in tick_fractions])
# Plot 2:
ax1 = fig.add_subplot(gs[0, 1])
ax1.plot(x2, y)
mini = min(x2)
maxi = max(x2)
dist = maxi - mini
ax1.set_xticks([mini + f * dist for f in tick_fractions])
plt.show()
如果您想限制小数位数,您可以在某处添加对 round
的调用。