我正在尝试创建一个带有链接 x 轴 st 的图。顶部和底部刻度/标签是单位测量(焦耳和千焦耳)。我看过 sharex 等的例子,但我的需求如下:
- 如何使轴链接到从第一个轴生成第二个刻度线/标签的位置
- 当改变一个轴的限制时,另一轴应自动更新
最简单的事情(一点也不优雅)是创建两个 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()
这会产生以下结果:
但是当我尝试对其中任何一个设置 x 轴限制时,事情就会崩溃。例如,做ax2.set_xlim(2,5)
只改变顶部的轴。
因为我已经知道 x1 和 x2 是相关的,所以我应该如何设置绘图,以便当我更改一个时,另一个会自动得到处理。
非常感谢
看来您想使用具有指定比例的寄生轴。有一个example http://matplotlib.org/examples/axes_grid/parasite_simple2.html这个在 matlpotlib 网站上,稍作修改的版本如下。
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()
这给出了下面的输出
如果您更改了限制ax
例如,极限ax_parasite
实例自动更新:
# Set limits of original axis (parasite axis are scaled automatically)
ax.set_ylim(0,12)
ax.set_xlim(500,4000)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)