如何在matplotlib中生成联动轴

3
我试图创建一个带有链接的x轴图,使得顶部和底部的刻度/标签都是单位(Joules和kJoules)的测量结果。我看到了一些使用sharex等的示例,但我的需求如下:
  1. 如何建立链接轴,在第二个轴上生成从第一个轴获取的刻度/标签
  2. 当更改一个轴的限制时,另一个轴应自动更新
最简单的方法(不够优雅)是创建两个x变量:
x1 = np.arange(0,10000,1000)
x2 = x1/1000.
y = np.random.randint(0,10,10)

fig, ax = plt.subplots()
ax.plot(x1, y, 'ro')

ax2 = ax.twiny()
ax2.plot(x2,y,visible=False)
plt.show()


这会生成以下结果:

okay

但当我尝试在它们中的任何一个上设置x轴限制时,事情就会出问题。例如,执行ax2.set_xlim(2,5)仅更改顶部轴。

noo, thats not what I want

由于我已经知道x1和x2是相关的,所以应该如何设置绘图,以便当我更改一个时,另一个自动处理。

感谢您的帮助。

1个回答

3

看起来你想使用一个指定比例的寄生坐标轴。Matplotlib网站上有一个示例,稍微修改后如下。

import matplotlib.transforms as mtransforms
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.parasite_axes import SubplotHost
import numpy as np

# Set seed for random numbers generator to make data recreateable
np.random.seed(1235) 

# Define data to be plotted
x1 = np.arange(0,10000,1000)
x2 = x1/1000.
y1 = np.random.randint(0,10,10)
y2 = y1/5.

# Create figure instance
fig = plt.figure()

# Make AxesHostAxesSubplot instance
ax = SubplotHost(fig, 1, 1, 1)

# Scale for top (parasite) x-axis: makes top x-axis 1/1000 of bottom x-axis
x_scale = 1000.
y_scale = 1.

# Set scales of parasite axes to x_scale and y_scale (relative to ax)
aux_trans = mtransforms.Affine2D().scale(x_scale, y_scale)

# Create parasite axes instance
ax_parasite = ax.twin(aux_trans) 
ax_parasite.set_viewlim_mode('transform')

fig.add_subplot(ax)

# Plot the data
ax.plot(x1, y1)
ax_parasite.plot(x2, y2)

# Configure axis labels and ticklabels
ax.set_xlabel('Original x-axis')
ax_parasite.set_xlabel('Parasite x-axis (scaled)')
ax.set_ylabel('y-axis')
ax_parasite.axis['right'].major_ticklabels.set_visible(False)

plt.show()

这将产生以下输出: enter image description here 如果您更改ax实例的限制,则ax_parasite实例的限制会自动更新:
# Set limits of original axis (parasite axis are scaled automatically)
ax.set_ylim(0,12)
ax.set_xlim(500,4000)

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接