我正在尝试使用链接的x轴s.t创建一个图。顶部和底部刻度/标签是单位的测量(焦耳和千焦耳)。我已经看过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是相关的,我应该如何设置绘图,这样当我更改一个时,另一个会自动处理。
非常感谢
答案 0 :(得分:3)
您似乎想要使用具有指定比例的寄生轴。 matlpotlib网站上有一个example,下面稍加修改版本。
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)