[英]Matplotlib Second x-axis with transformed values
I have been using a piece of code (based on the solution to another's problem given here ) to create plots of spectroscopic data with two x-axis. 我一直在使用一段代码(基于此处给出的另一个问题的解决方案)来创建具有两个x轴的光谱数据图。 The first (bottom) is in frequency units, the second (top) is just transformed to wavelength units (wavelength = 3E8/frequency).
第一个(底部)是频率单位,第二个(顶部)只是转换为波长单位(波长= 3E8 /频率)。 This was working well until I upgraded MPL to 1.4.2 after which the values on the upper axis are just the same as those on the lower axis (see example).
这很有效,直到我将MPL升级到1.4.2,之后上轴的值与下轴上的值相同(参见示例)。
A MWE (an exact copy from the MPL mailing list) is: MWE(来自MPL邮件列表的精确副本)是:
from matplotlib.transforms import Transform, BlendedGenericTransform, IdentityTransform
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid.parasite_axes import SubplotHost
import numpy as np
c = 3.e2
class Freq2WavelengthTransform(Transform):
input_dims = 1
output_dims = 1
is_separable = False
has_inverse = True
def transform(self, tr):
return c/tr
def inverted(self):
return Wavelength2FreqTransform()
class Wavelength2FreqTransform(Freq2WavelengthTransform):
def inverted(self):
return Freq2WavelengthTransform()
aux_trans = BlendedGenericTransform(Freq2WavelengthTransform(),
IdentityTransform())
fig = plt.figure(2)
ax_GHz = SubplotHost(fig, 1,1,1)
fig.add_subplot(ax_GHz)
ax_GHz.set_xlabel("Frequency (GHz)")
xvals = np.arange(199.9, 999.9, 0.1)
#make some test data
data = np.sin(0.03*xvals)
ax_mm = ax_GHz.twin(aux_trans)
ax_mm.set_xlabel('Wavelength (mm)')
ax_mm.set_viewlim_mode("transform")
ax_mm.axis["right"].toggle(ticklabels=False)
ax_GHz.plot(xvals, data)
ax_GHz.set_xlim(200, 1000)
plt.draw()
plt.show()
This produces 这产生了
Can any one advise me how to address this in MPL 1.4.2? 谁能告诉我如何在MPL 1.4.2中解决这个问题?
Using a combination of Adobe's answer from the thread linked to in wwii's comment, and your own code. 使用来自wwii评论中链接的线程的Adobe答案和您自己的代码。
import numpy as np
import matplotlib.pyplot as plt
c=3.e2
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()
xvals = np.arange(199.9, 999.9, 0.1)
data = np.sin(0.03*xvals)
ax1.plot(xvals, data)
ax1Ticks = ax1.get_xticks()
ax2Ticks = ax1Ticks
def tick_function(X):
V = c/X
return ["%.3f" % z for z in V]
ax2.set_xticks(ax2Ticks)
ax2.set_xbound(ax1.get_xbound())
ax2.set_xticklabels(tick_function(ax2Ticks))
ax1.set_xlabel("Frequency (GHz)")
ax2.set_xlabel('Wavelength (mm)')
ax1.grid(True)
plt.ylim(ymin=-1.1,ymax=1.1)
plt.show()
This produces; 这产生;
I hope this helps! 我希望这有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.