Matplotlib:次轴,其值从主轴映射 [英] Matplotlib: Secondary axis with values mapped from primary axis

查看:99
本文介绍了Matplotlib:次轴,其值从主轴映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张图显示x4与y:

y是其他变量的对数,例如q(即y = log(q)) q的值是外行人员在阅读此图时将理解的内容.

我想在图形的右侧设置辅助轴,其中线与左侧轴在相同的垂直位置,但是标签被等效的q值替换-即exp(y )-小数点后2位.

是否有一种有效的方法来创建辅助轴,该轴是否从主要y轴进行映射?

我正在使用matplotlib中的pyplot.一些示例起始代码:

import numpy as np
import matplotlib.pyplot as plt

q = np.random.rand(100,)
y = np.log(q)
x4 = np.random.rand(100,)

plt.scatter(x4, y)

我想添加第二个轴,该轴的垂直位置和间距与主轴相同,但标签由exp(y)代替.还包括轴标签"q".

谢谢

解决方案

我在这里的建议是使用双轴并将其与原始轴共享以固定刻度位置.然后,您可以使用FuncFormatter为刻度线提供正确的标签.这样做的好处是您无需事先确定图的限制,而可以在图内自由缩放和平移.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter


f = lambda q: np.log(q)
finv = lambda x: np.exp(x)

x = np.random.rand(100,)
y = f(np.random.rand(100,))


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

ax.scatter(x, y)

ax2.yaxis.set_major_formatter(FuncFormatter(lambda x,pos: f"{finv(x):.2f}"))
plt.show()

I have a graph showing x4 vs y:

y is the log of some other variable, say q (i.e. y = log(q) ) the value of q is what the layperson will understand when reading this graph.

I want to set up a secondary axis on the right side of the graph, where the lines are at the same vertical position as the left-hand axis, but the label is replaced by the equivalent q value - i.e. exp(y) - to 2 decimal places.

Is there an efficient way to create a secondary axis which does this mapping from the primary y axis?

I'm using pyplot from matplotlib. Some example starting code:

import numpy as np
import matplotlib.pyplot as plt

q = np.random.rand(100,)
y = np.log(q)
x4 = np.random.rand(100,)

plt.scatter(x4, y)

I want to add a second axis, which has the same vertical positions and spacing as the primary axis, but the labels are replaced by exp(y). Also include an axis label "q".

Thank you

解决方案

My suggestion here would be to use a twin axes and share it will the original axes to fix the tick positions. You may then use a FuncFormatter to give the ticks the correct labels. The advantage of this is that you do not need to fix the limits of the plot a priori and can freely zoom and pan inside the plot.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter


f = lambda q: np.log(q)
finv = lambda x: np.exp(x)

x = np.random.rand(100,)
y = f(np.random.rand(100,))


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

ax.scatter(x, y)

ax2.yaxis.set_major_formatter(FuncFormatter(lambda x,pos: f"{finv(x):.2f}"))
plt.show()

这篇关于Matplotlib:次轴,其值从主轴映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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