matplotlib - 添加与第一个 y 轴相关的第二个 y 轴

标签 matplotlib plot

我希望你们中的一个人可以提供帮助。我有一个带有一个 y 轴值和一个与这些 y 值对应的 x 轴的图。我想在图的右侧添加第二个 y 轴。将出现在第二个 y 轴上的值由第一个 y 轴值通过某种关系确定:例如,y2 可能是 y2 = y1**2 - 100 .如何制作第二个 y 轴,其值由 y1 值确定,以便 y2 值与 y 轴上的 y1 值正确对齐?

最佳答案

双轴

添加第二个 y 轴可以通过创建双轴来完成,ax2 = ax.twinx() .
可以使用其限制设置此轴的比例,ax2.set_ylim(y2min, y2max) . y2min, y2max 的值可以使用一些已知的关系(例如作为函数实现)从左轴的限制计算。

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(0)

x = np.linspace(0,50,101)
y = np.cumsum(np.random.normal(size=len(x)))+20.

fig, ax = plt.subplots()
ax2 = ax.twinx()

ax.plot(x,y, color="#dd0011")
ax.set_ylabel("Temperature [Celsius]")
ax2.set_ylabel("Temperature [Fahrenheit]")

# set twin scale (convert degree celsius to fahrenheit)
T_f = lambda T_c: T_c*1.8 + 32.
# get left axis limits
ymin, ymax = ax.get_ylim()
# apply function and set transformed values to right axis limits
ax2.set_ylim((T_f(ymin),T_f(ymax)))
# set an invisible artist to twin axes 
# to prevent falling back to initial values on rescale events
ax2.plot([],[])

plt.show()

enter image description here

副轴

从 matplotlib 3.1 开始可以使用 secondary_yaxis .这负责自动同步限制。作为输入,需要转换函数及其逆函数。
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(0)

x = np.linspace(0,50,101)
y = np.cumsum(np.random.normal(size=len(x)))+20.

# Convert celsius to Fahrenheit
T_f = lambda T_c: T_c*1.8 + 32.
# Convert Fahrenheit to Celsius
T_c = lambda T_f: (T_f - 32.)/1.8

fig, ax = plt.subplots()
ax2 = ax.secondary_yaxis("right", functions=(T_f, T_c))

ax.plot(x,y, color="#dd0011")
ax.set_ylabel("Temperature [Celsius]")
ax2.set_ylabel("Temperature [Fahrenheit]")

plt.show()

输出与上面相同,但正如您所见,不需要设置任何限制。

关于matplotlib - 添加与第一个 y 轴相关的第二个 y 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43149703/

相关文章:

python - 使 plt.colorbar 扩展到 vmin/vmax 前后的步骤

python - 将每个 seaborn 图形附加到 for 循环内的 PDF

python - 如何使 x 和 y 轴标签的文本大小以及 matplotlib 和 prettyplotlib 图形上的标题更大

r - 如何停止图形设备窗口切断 plot() 的边缘?

python - 在 Python 的 Line2D 中使用属性 "figsize"的等价物是什么

python - Matplotlib 在 imshow 图中居中/对齐刻度

python matplotlib.补丁: draw a Circle patch but keep only part of the circle

linux - 是否可以在 gnuplot 中绘制正态概率分布

r - ggplot sec_axis 我可以使用向量作为反式公式吗?

r - mfrow(r 中的多个图形)