【问题标题】:Using Pylab Subplots Function: Lining up subplots with different x axes使用 Pylab 子图功能:用不同的 x 轴排列子图
【发布时间】:2016-11-08 19:46:49
【问题描述】:

我正在使用 Pylab (pl) subplots 函数如下:

f, (ax1, ax2, ax3, ax4) = pl.subplots(4, sharex=True, sharey=False)

假设 t0、t1、t2 和 t3 是按时间顺序排列的四个时间戳。轴对象 ax1 和 ax2 在时间戳 t0 和 t2 之间生成降水和气温数据的子图,共有 100 个数据点。轴对象 ax3 和 ax4 在时间戳 t1 和 t3 之间生成相对湿度和风数据的子图,共有 500 个数据点。

两个时间数组都使用以下方法转换为十进制数:

import matplotlib.dates as dates
time_numbers1 = dates.datestr2num(time_array1)
time_numbers2 = dates.datestr2num(time_array2)

我遇到的问题并不奇怪:当我运行我的代码时,生成的图形显示 ax1 和 ax2 数据失真,与 ax3 和 ax4 中的数据不相符。

我知道我的问题与我对这个子图设置的使用过于简单有关:

sharex=True

有没有人有处理这个绘图问题的建议/想法?需要明确的是,这不是一个做或死的情况,因为我总是可以摆弄数据(例如,零填充、插值、平均)来让数据对齐。然而,这是很多数据,所以我很好奇是否有任何聪明的绘图解决方案。

【问题讨论】:

    标签: matplotlib


    【解决方案1】:

    恐怕plt.subplots是你做了太多你不知道的事情。如果您想要简单的图形,它会很好,但如果您想做一些稍微高级的事情,通常最好创建自己的图形并手动添加子图。即

    import matplotlib.pyplot as plt
    fig = plt.figure()
    ax1 = fig.add_subplot(4, 1, 1)
    ax2 = fig.add_subplot(4, 1, 2, sharex=ax1)
    ax3 = fig.add_subplot(4, 1, 3)
    ax4 = fig.add_subplot(4, 1, 4, sharex=ax3)
    

    这应该强制只共享两个 x 轴,但是是两对。在这种情况下,我会说与其堆叠它们,不如使用网格更好,因为

    import matplotlib.pyplot as plt
    fig = plt.figure()
    ax1 = fig.add_subplot(2, 2, 1)
    ax2 = fig.add_subplot(2, 2, 2)
    ax3 = fig.add_subplot(2, 2, 3, sharex=ax1)
    ax4 = fig.add_subplot(2, 2, 4, sharex=ax3)
    

    希望对你有帮助!

    【讨论】:

    • 谢谢你,@pathoren!这正是我所需要的。
    • 好!如果您觉得有用,请采纳答案。
    • 是的,我昨天试图找到如何“接受”你的答案,但我不知道如何。当然,一旦我知道该怎么做,这很容易:只需单击灰色的复选标记。非常好。
    猜你喜欢
    • 2015-03-30
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 2017-08-06
    • 2013-02-12
    • 1970-01-01
    • 2020-04-01
    • 1970-01-01
    相关资源
    最近更新 更多