Matplotlib - imshow twiny() 问题 [英] Matplotlib - imshow twiny() problems

查看:34
本文介绍了Matplotlib - imshow twiny() 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在matplotlib imshow()图中使用两个相互依赖的x轴.我有底部 x 轴作为半径的平方,我希望顶部只是半径.到目前为止,我已经尝试过:

I am trying to have two inter-depedent x-axis in a matplotlib imshow() plot. I have bottom x-axis as the radius squared and I want the top as just the radius. I have tried so far:

ax8 = ax7.twiny()
ax8._sharex = ax7
fmtr = FuncFormatter(lambda x,pos: np.sqrt(x) )
ax8.xaxis.set_major_formatter(fmtr)
ax8.set_xlabel("Radius [m]")

其中 ax7 是 y 轴和底部 x 轴(或半径的平方).而不是获得sqrt(x_bottom)作为顶部的刻度,我得到的范围是0到1.如何解决此问题?

where ax7 is the y-axis and the bottom x-axis (or radius squared). Instead of getting the sqrt (x_bottom) as the ticks at the top I just get a range from 0 to 1. How can I fix this?

非常感谢.

推荐答案

你误解了 twiny 的作用.它使完全独立 x 轴与共享 y 轴.

You're misunderstanding what twiny does. It makes a completely independent x-axis with a shared y-axis.

您想要做的是有一个带有链接轴的不同格式化程序(即共享轴限制,但没有其他内容).

What you want to do is have a different formatter with a linked axis (i.e. sharing the axis limits but nothing else).

执行此操作的简单方法是手动设置双联轴的轴限制:

The simple way to do this is to manually set the axis limits for the twinned axis:

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

fig, ax1 = plt.subplots()
ax1.plot(range(10))

ax2 = ax1.twiny()
formatter = FuncFormatter(lambda x, pos: '{:0.2f}'.format(np.sqrt(x)))
ax2.xaxis.set_major_formatter(formatter)

ax2.set_xlim(ax1.get_xlim())

plt.show()

但是,一旦缩放或与图进行交互,您会注意到轴是未链接的.

However, as soon as you zoom or interact with the plot, you'll notice that the axes are unlinked.

您可以在共享 x 轴和 y 轴的相同位置添加一个轴,但随后也会共享刻度格式器.

You could add an axes in the same position with both shared x and y axes, but then the tick formatters are shared, as well.

因此,最简单的方法是使用寄生轴.

Therefore, the easiest way to do this is using a parasite axes.

作为一个简单的例子:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
from mpl_toolkits.axes_grid1.parasite_axes import SubplotHost

fig = plt.figure()
ax1 = SubplotHost(fig, 1,1,1)
fig.add_subplot(ax1)

ax2 = ax1.twin()

ax1.plot(range(10))

formatter = FuncFormatter(lambda x, pos: '{:0.2f}'.format(np.sqrt(x)))
ax2.xaxis.set_major_formatter(formatter)

plt.show()

这幅图和之前的图一开始看起来是一样的.当您与图进行交互(例如缩放/平移)时,差异将变得明显.

Both this and the previous plot will look identical at first. The difference will become apparent when you interact (e.g. zoom/pan) with the plot.

这篇关于Matplotlib - imshow twiny() 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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