添加与第一个 y 轴相关的第二个 y 轴 [英] Adding a second y-axis related to the first y-axis

查看:30
本文介绍了添加与第一个 y 轴相关的第二个 y 轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I hope one of you may be able to help. I have a plot with one y-axis value and one x-axis corresponding to these y values. I want to add a second y-axis on the right hand side of the plot. The values that will appear on the second y-axis are determined through the first y-axis values by some relation: for example, y2 might be y2 = y1**2 - 100. How do I make a second y-axis which has its values determined by the y1 values, so that the y2 values correctly align with their y1 values on the y-axis?

推荐答案

双轴

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

twin axis

Adding a second y axis can be done by creating a twin axes, ax2 = ax.twinx(). The scale of this axes can be set using its limits, ax2.set_ylim(y2min, y2max). The values of y2min, y2max can be calculated using some known relationship (e.g. implemented as a function) from the limits of the left axis.

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

从 matplotlib 3.1 开始,可以使用 secondary_yaxis.这负责自动同步限制.作为输入,需要转换函数及其逆函数.

From matplotlib 3.1 onwards one can use a secondary_yaxis. This takes care of synchronizing the limits automatically. As input one needs the conversion function and its inverse.

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

输出和上面一样,但是你可以看到不需要设置任何限制.

The output is the same as above, but as you can see one does not need to set any limits.

这篇关于添加与第一个 y 轴相关的第二个 y 轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆