我有一个共享 x 轴上有两个 y 轴的图,我想让它们在 y=0 处对齐,以便我可以绘制一条水平线来突出显示零刻度。目前两个轴没有对齐,我必须画两条线,这很糟糕。我怎样才能做到这一点?
我遇到了同样的问题,我所做的是根据最小与最大限制的比率来更改 y 轴的范围。如果将 y 轴的比例设置为相同,则零点应该相同。
fig, ax1 = plt.subplots()
ax1.plot(...) # Plot first data set
ax2 = ax1.twinx()
ax2.plot(...) # Plot second data set
ax1_ylims = ax1.axes.get_ylim() # Find y-axis limits set by the plotter
ax1_yratio = ax1_ylims[0] / ax1_ylims[1] # Calculate ratio of lowest limit to highest limit
ax2_ylims = ax2.axes.get_ylim() # Find y-axis limits set by the plotter
ax2_yratio = ax2_ylims[0] / ax2_ylims[1] # Calculate ratio of lowest limit to highest limit
# If the plot limits ratio of plot 1 is smaller than plot 2, the first data set has
# a wider range range than the second data set. Calculate a new low limit for the
# second data set to obtain a similar ratio to the first data set.
# Else, do it the other way around
if ax1_yratio < ax2_yratio:
ax2.set_ylim(bottom = ax2_ylims[1]*ax1_yratio)
else:
ax1.set_ylim(bottom = ax1_ylims[1]*ax2_yratio)
plt.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)
这是我的第一个答案,所以我希望它足够并且没问题。
假设您创建了具有共享轴的图,您只需要修改 y 的范围,使其以零为中心或在两个图中具有类似的偏移乘数(即为ax.set_ylim(-6,6)两个图设置)。下面的代码是一个例子。
from matplotlib import pyplot as plt
import numpy as np
#Create some Fake Data
x =np.arange(-10,10)
y = x+np.random.rand(20)
y2 = 0.5*x-3.*np.random.rand(20)
#Figure
fig = plt.figure(figsize=(12,6))
#First subplot with zero line not even
ax1 = plt.subplot(121)
ax2 = ax1.twinx()
ax1.plot(x,y,c='r')
ax2.plot(x,y2,c='b')
ax1.axhline(0)
#Second Subplot with zero line the same on both axes
ax3 = plt.subplot(122)
ax4 = ax3.twinx()
ax3.plot(x,y,c='r')
ax4.plot(x,y2,c='b')
ax3.axhline(0)
#If you set your limits on both sides to have the same interval you will get the same zero line
ax3.set_ylim(-10,10)
ax4.set_ylim(-6,6)
plt.show()
Run Code Online (Sandbox Code Playgroud)
我发现这个优秀的库可以对齐轴并保持自动缩放。
pip install mpl-axes-aligner
import numpy as np
import matplotlib.pyplot as plt
import mpl_axes_aligner
x = np.arange(0.0, 30, 0.1)
y1 = 0.1 * x * np.sin(x)
y2 = 0.001*x**3 - 0.03*x**2 + 0.12*x
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
ax1.plot(x, y1, color='blue', label='Plot 1')
ax2.plot(x, y2, color='red', label='Plot 2')
# Align y = 0 of ax1 and ax2 with the center of figure.
mpl_axes_aligner.align.yaxes(ax1, 0, ax2, 0, 0.5)
plt.show()
Run Code Online (Sandbox Code Playgroud)
这个包是由ryotuk开发的,上面的使用示例来自他的包的文档。