首页 > 解决方案 > 两行在 matplotlib 中使用不同的 xticks 共享一个不可见的 xdata

问题描述

我有两组数组x1, y1, t1x2, y2, t1——x数据、 y数据和时间测量。

我想将这两个集合绘制为线,并以时间作为x参数 in plot(),以便这些线相对于事件的时间优先级对齐。

但是,我还希望以 xlabels 的形式(例如在图的顶部和底部)查看相应的x1x2在图上,以及有两个y值刻度(即在左侧和右侧如图)。


import numpy as np
t1 = np.linspace(0, 10, 10)
y1 = np.arange(10)
x1 = (np.cumsum(np.random.rand(10)) * 1000000000).astype(int)
x1 = (x1 /  100000).astype(int) * 10

x2 = (np.cumsum(np.random.rand(10)) * 1000000000).astype(int)
x2 = (x2 / 1000000).astype(int)
y2 =  2 * np.arange(10)
t2 = np.linspace(0, 10, 10) + 2


from matplotlib import pyplot as plt 
fig, ax1 = plt.subplots()

ax1.plot(t1, y1)
ax1.set_ylabel("y1 label")
ax1.set_xticklabels(x1)
ax1.set_xlabel("x1 label")


ax2 = ax1.twinx()
ax2.plot(t2, y2, c='r')
ax2.set_ylabel("y2 label")

ax3 = ax2.twiny()
ax3.xaxis.set_ticks_position('top')

ax3.set_xticklabels(x2);
ax3.set_xlabel("x2 label")

生成的代码 在此处输入图像描述 很好,但有两个问题:

  1. xlabels未与数据对齐:绘图上的蓝线从 x1 ticklabel 开始104500,而x1[0] = 29380.
  2. 我无法为和刻度应用sci格式,即行x1x2
ax1.ticklabel_format(style='sci', axis='x', scilimits=(0,0))  

失败This method only works with the ScalarFormatter,这是合理的,因为我已经替换了刻度标签,而不是刻度本身。另一方面,我不能分配x1xticks,因为这会改变 xaxis 的限制。

我怎样才能克服这两个问题?

标签: pythonmatplotlib

解决方案


推荐阅读