【问题标题】:Matplotlib Second x-axis with transformed valuesMatplotlib 具有转换值的第二个 x 轴
【发布时间】:2015-01-23 14:37:44
【问题描述】:

我一直在使用一段代码(基于给定here 的另一个问题的解决方案)来创建具有两个 x 轴的光谱数据图。第一个(底部)是频率单位,第二个(顶部)只是转换为波长单位(波长 = 3E8/频率)。这一直很好,直到我将 MPL 升级到 1.4.2 之后,上轴上的值与下轴上的值相同(参见示例)。

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

这会产生

谁能告诉我如何在 MPL 1.4.2 中解决这个问题?

【问题讨论】:

标签: python matplotlib


【解决方案1】:

结合使用 Adob​​e 在 wwii 评论中链接到的 thread 的答案和您自己的代码。

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

这会产生;

我希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-17
    • 1970-01-01
    • 2011-12-07
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多