【问题标题】:Matplotlib: plot x/y coordinates with Two x-Axis with inverse scalingMatplotlib:使用两个 x 轴绘制 x/y 坐标并进行反向缩放
【发布时间】:2013-07-16 11:25:51
【问题描述】:

我想创建一个带有两个 x 轴和一个 y 轴的特殊图。底部 X 轴的值增加,顶部 X 轴的值减小。我有一个 x-y 对,我想在一个 x 轴上绘制 y 并在顶部 x' 轴上以不同的比例绘制:(x' = f(x))

在我的例子中,xx' 之间的转换是 x' = c/x,其中 c 是一个常数。我找到了一个例子here,它处理这种转换。不幸的是,这个例子对我不起作用(没有错误消息,只是没有转换输出)。

我正在使用python 3.3matplotlib 1.3.0rc4 (numpy 1.7.1)

有人知道使用 matplotlib 的便捷方法吗?

编辑: 我在 stackoverflow (https://stackoverflow.com/a/10517481/2586950) 上找到了答案,它帮助我找到了想要的情节。只要我可以发布图片(由于声誉限制),如果有人感兴趣,我会在这里发布答案。

【问题讨论】:

    标签: python numpy matplotlib


    【解决方案1】:

    我不确定这是否是您正在寻找的,但无论如何它都在这里:

    import pylab as py
    x = py.linspace(0,10)
    y = py.sin(x)
    c = 2.0
    
    # First plot
    ax1 = py.subplot(111)
    ax1.plot(x,y , "k")
    ax1.set_xlabel("x")
    
    # Second plot
    ax2 = ax1.twiny()
    ax2.plot(x / c, y, "--r")
    ax2.set_xlabel("x'", color='r')
    for tl in ax2.get_xticklabels():
        tl.set_color('r')
    

    我猜这就是你的意思

    我有一个 x-y 对,我想在一个 x 轴上和一个 x' 轴下以不同的比例绘制 y。

    但如果我错了,我深表歉意。

    【讨论】:

    • 嘿,哇,快速回答。原则上最终的图表应该是这样的,唯一的问题是:x' = c/x,它是一个反比关系 - 如果我通过在 ax2.plot(x / c, y, "--r") 这两个函数不再一致了。
    • 当然不是,您仍然在绘制相同的 y 数据,但绘制的是完全不同的比例。所以它仍然是一个 sin 函数,但被拉伸为 x->inf。在 x=0 时您也会遇到问题。试着用铅笔和纸画出你想要的东西。
    • 我认为可以肯定地说,大多数在这里发帖的人都知道函数的行为取决于其参数和绘制的轴。我只是很难说清楚,对不起。正如有问题的编辑中所述,我找到了答案。我会尽快发布它,并澄清所要求的内容。
    【解决方案2】:

    以下代码的输出对我来说是令人满意的——除非有更方便的方法,否则我会坚持下去。

    import matplotlib.pyplot as plt
    import numpy as np
    
    plt.plot([1,2,5,4])
    ax1 = plt.gca()
    ax2 = ax1.twiny()
    
    new_tick_locations = np.array([.1, .3, .5, .7,.9]) # Choosing the new tick locations
    inv = ax1.transData.inverted()
    x = []
    
    for each in new_tick_locations:
        print(each)
        a = inv.transform(ax1.transAxes.transform([each,1])) # Convert axes-x-coordinates to data-x-coordinates
        x.append(a[0])
    
    c = 2
    x = np.array(x)
    def tick_function(X):
        V =  c/X
        return ["%.1f" % z for z in V]
    ax2.set_xticks(new_tick_locations) # Set tick-positions on the second x-axes
    ax2.set_xticklabels(tick_function(x)) # Convert the Data-x-coordinates of the first x-axes to the Desired x', with the tick_function(X)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-26
      • 1970-01-01
      • 2016-10-27
      • 1970-01-01
      • 1970-01-01
      • 2015-06-10
      • 2011-04-24
      相关资源
      最近更新 更多