如何在子图中对齐对数刻度?
How to align logarithmic scale ticks across subplots?
我想固定刻度在对数刻度上的位置,以便它们在每个子图中都相同(参见图像中的红色注释)。
我的代码如下所示:
ax = fig.add_subplot(2,2, axis)
ax2 = ax.twinx()
ax2.set_yscale('log')
ax2.set_ylim(0,100)
现在,set_yscale=('log')
优化了每个子图的刻度间距。我更喜欢采用右上子图的刻度间距。
您可以通过获取左侧双轴的限制并将其设置为右侧双轴的限制来实现此目的。
考虑以下工作示例。对要对齐轴的子图执行此过程。
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8, 3))
axl = fig.add_subplot(121)
axr = fig.add_subplot(122)
ax1 = axl.twinx()
ax1.plot(np.logspace(-2, 3, 5))
ax1.set_yscale('log')
ax2 = axr.twinx()
ax2.plot(np.logspace(0, 3, 5))
ax2.set_yscale('log')
ax2.set_ylim(ax1.get_ylim()) # <-- This is the key line
plt.tight_layout()
plt.show()
OP 的解决方案:
绘制虚拟曲线并设置alpha=0
。确保曲线跨越 y_min 和 y_max。
fig = plt.figure()
axes = [1,2,3,4]
for axis in axes:
ax = fig.add_subplot(2,2, axis)
ax2 = ax.twinx()
ax2.set_yscale('log')
ax2.plot(x_dummy, y_dummy, alpha=0) # <-- dummy plot
x_real, y_real = func_that_loads_data() # <-- your interesting plot
curve1 = ax2.plot(x_real, y_real)
plt.show()
Sheldore 提供的解决方案实施起来不切实际,因为我使用 for-loop 绘制数据(这是不可避免的,除非我增加变量的数量)。
因为我在每次迭代时都覆盖了 ax
变量,所以我必须将 y-limit 保存为全局变量。 Read here why global variables should be avoided.
ax = fig.add_subplot(2,2, axis)
ax2 = ax.twinx()
ax2.set_yscale('log')
if axis == 1:
global yscale
yscale = ax2.get_ylim() # <-- where the magic happens
elif axis > 1:
ax2.set_ylim(yscale)
我想固定刻度在对数刻度上的位置,以便它们在每个子图中都相同(参见图像中的红色注释)。 我的代码如下所示:
ax = fig.add_subplot(2,2, axis)
ax2 = ax.twinx()
ax2.set_yscale('log')
ax2.set_ylim(0,100)
现在,set_yscale=('log')
优化了每个子图的刻度间距。我更喜欢采用右上子图的刻度间距。
您可以通过获取左侧双轴的限制并将其设置为右侧双轴的限制来实现此目的。
考虑以下工作示例。对要对齐轴的子图执行此过程。
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8, 3))
axl = fig.add_subplot(121)
axr = fig.add_subplot(122)
ax1 = axl.twinx()
ax1.plot(np.logspace(-2, 3, 5))
ax1.set_yscale('log')
ax2 = axr.twinx()
ax2.plot(np.logspace(0, 3, 5))
ax2.set_yscale('log')
ax2.set_ylim(ax1.get_ylim()) # <-- This is the key line
plt.tight_layout()
plt.show()
OP 的解决方案:
绘制虚拟曲线并设置alpha=0
。确保曲线跨越 y_min 和 y_max。
fig = plt.figure()
axes = [1,2,3,4]
for axis in axes:
ax = fig.add_subplot(2,2, axis)
ax2 = ax.twinx()
ax2.set_yscale('log')
ax2.plot(x_dummy, y_dummy, alpha=0) # <-- dummy plot
x_real, y_real = func_that_loads_data() # <-- your interesting plot
curve1 = ax2.plot(x_real, y_real)
plt.show()
Sheldore 提供的解决方案实施起来不切实际,因为我使用 for-loop 绘制数据(这是不可避免的,除非我增加变量的数量)。
因为我在每次迭代时都覆盖了 ax
变量,所以我必须将 y-limit 保存为全局变量。 Read here why global variables should be avoided.
ax = fig.add_subplot(2,2, axis)
ax2 = ax.twinx()
ax2.set_yscale('log')
if axis == 1:
global yscale
yscale = ax2.get_ylim() # <-- where the magic happens
elif axis > 1:
ax2.set_ylim(yscale)