matplotlib:将两个y轴围绕零对齐

时间:2019-04-12 07:42:52

标签: matplotlib

我有一个带有两个y轴的图,我想使它们在零刻度处对齐,以便我可以画一条水平线以突出显示0刻度。目前两个轴未对齐,我必须绘制两条直线,这很糟糕。
我该如何实现?

enter image description here

3 个答案:

答案 0 :(得分:2)

我遇到了同样的问题,我所做的是根据最小与最大限制的比率更改 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()

这是我的第一个答案,所以我希望它足够好。

答案 1 :(得分:0)

假设您使用共享轴创建了图,则只需将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()

enter image description here

答案 2 :(得分:0)

我发现this excellent library可以对齐轴并保持自动缩放。

安装

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()

输出

Output graph

信用

此软件包由ryotuk开发,上面的用法示例来自其软件包的文档。