twinx() 和 axhline

4 投票
2 回答
3363 浏览
提问于 2025-04-17 19:45

在使用twinx()之后,如果立刻调用axhline来画水平线,这条线还是会跟着第一个y轴的坐标走。

有没有什么建议可以让它跟第二个y轴的坐标对齐呢?

2 个回答

1

如果你无法直接获取到 twinx() 的返回值(比如说这个函数是被 Pandas 自动调用的),你仍然可以通过 Axes 对象的 left_axright_ax 属性来访问左边和右边的坐标轴。

这两个属性中只会有一个存在,因为它们是相互连接的。

  • 如果你有左边坐标轴的引用,它的 right_ax 属性会指向连接的右边坐标轴。
  • 如果你有右边坐标轴的引用,它的 left_ax 属性会指向连接的左边坐标轴。

举个例子:

df = pandas.DataFrame({'d1': numpy.random.rand(10), 
                       'd2': numpy.random.rand(10) * 10})
ax = df.plot(secondary_y=['d2'])  # returns the left axis
ax.axhline(y=0.5, alpha=0.5)      # draw a line from it
ax.right_ax.axhline(y=10, color="red", alpha=0.5)  # draw a line from the right axis

Pandas plot() output

2

你可以通过坐标轴对象来调用 axhline 方法,就像下面的例子那样,或者使用 sca 来设置当前的坐标轴。

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 10, 0.1)
y1 = np.sin(x)
y2 = 2.0 * np.cos(x)

fig = plt.figure()
ax1 = plt.subplot(111)
ax2 = ax1.twinx()

ax1.axhline( 0.5, 0.1, 0.5, color='r', lw=3)
ax2.axhline(-0.5, 0.5, 0.9, color='b', lw=3)

ax1.plot(x, y1, 'r', lw=2)
ax2.plot(x, y2, 'b', lw=2)

plt.show()

撰写回答