首页 > 解决方案 > 在 Matplotlib 的插图中使用 twiny()

问题描述

我正在尝试将第二个 x 轴添加到我使用InsetPositionfrom创建的插图中mpl_toolkits.axes_grid1.inset_locator(例如https://scipython.com/blog/inset-plots-in-matplotlib/之后),但第二个 x 轴没有似乎没有出现,我不知道为什么。

这是我正在使用的代码:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.gca()

from mpl_toolkits.axes_grid1.inset_locator import InsetPosition
zoom_ax = fig.add_axes([0,0,1,1])
zoom_ax.set_axes_locator(InsetPosition(ax, [0.6, 0.6, 0.3, 0.3]))

def expansion(z):
    return 1.0 / (1.0 + z)

def redshift(a):
    return 1.0 / a - 1.0

def tick_function(a):
    return ["%.1f" % z for z in redshift(a)]

z_ticks = np.array([0.0, 0.5, 1.0, 2.0, 5.0, 100.0])
a_ticks = expansion(z_ticks)

twin_ax = zoom_ax.twiny()
twin_ax.set_xticks(a_ticks)
twin_ax.set_xticklabels(tick_function(a_ticks))
twin_ax.set_xlim(zoom_ax.get_xlim())

xmin, xmax = 0.0, 1.0
x = np.linspace(xmin, xmax)
zoom_ax.plot(x, np.sin(x))
zoom_ax.set_xlim(xmin, xmax)

plt.show()

这会产生以下图 - 没有任何twiny()轴:

上述代码的结果

标签: python-3.xmatplotlib

解决方案


显然使用 bytwiny()有问题(不知道这是否是一个错误)。如果您对 重复命令,生成的图看起来就像我所期望的那样(我省略了轴刻度命令以使我的示例图更易于理解):axes_locatorzoom_axset_axes_locator()twin_ax

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.gca()

from mpl_toolkits.axes_grid1.inset_locator import InsetPosition
zoom_ax = fig.add_axes([0,0,1,1])
zoom_ax.set_axes_locator(InsetPosition(ax, [0.6, 0.6, 0.3, 0.3]))

def expansion(z):
    return 1.0 / (1.0 + z)

def redshift(a):
    return 1.0 / a - 1.0

def tick_function(a):
    return ["%.1f" % z for z in redshift(a)]

z_ticks = np.array([0.0, 0.5, 1.0, 2.0, 5.0, 100.0])
a_ticks = expansion(z_ticks)

twin_ax = zoom_ax.twiny()
##twin_ax.set_xticks(a_ticks)
##twin_ax.set_xticklabels(tick_function(a_ticks))
twin_ax.set_xlim(zoom_ax.get_xlim())

xmin, xmax = 0.0, 1.0
x = np.linspace(xmin, xmax)
zoom_ax.plot(x, np.sin(x))
zoom_ax.set_xlim(xmin, xmax)

##the extra lines
twin_ax.set_axes_locator(InsetPosition(ax, [0.6, 0.6, 0.3, 0.3]))
x2 = np.linspace(xmin, 2*xmax)
twin_ax.plot(x2,np.cos(x2),'r')
twin_ax.set_xlim(xmin, 2*xmax)

plt.show()

这会产生以下图:

上述代码的结果


推荐阅读