【问题标题】:Force all subplots to use the same axis range when plotting with Pandas使用 Pandas 绘图时强制所有子图使用相同的轴范围
【发布时间】:2014-09-12 18:18:56
【问题描述】:

我正在使用“by”选项使用 Pandas 创建分面图,如下所示:

import pandas as pd
pd.Series(randn(1000)).hist(by=randint(0, 4, 1000), figsize=(6, 4))

这很棒。但是,我希望 x 轴和 y 轴在所有图中都相同。有没有内置的方法来做到这一点?在 ggplot 中,我会使用 scales="fixed" 选项,但我看不到 Pandas 绘图中内置的类似内容。

显然,我的后备方案是写几行简短的代码来为我做这件事,但如果有一种自动的方法可以做到这一点,我想使用它。

【问题讨论】:

    标签: python plot pandas


    【解决方案1】:

    您正在寻找可以通过将sharex=Truesharey=True 传递为keyword arguments to hist 来启用的共享x 轴和y 轴。

    这将通过matplotlib 的子图机制创建子图。与手动定位子图和删除轴相比,这样做的好处是您可以使用大型 matplotlib 工具集来操纵轴,例如

    import matplotlib.pyplot as plt
    import pandas as pd
    pd.Series(randn(1000)).hist(by=randint(0, 4, 1000), figsize=(6, 4),
                                sharex=True, sharey=True)
    
    ax = plt.gca()
    ax.set_xlim(-10, 10)
    ax.set_ylim(0, 100)
    

    【讨论】:

    • 作为旁注,目前(2014 年 9 月)Pandas 中似乎存在一个错误,如果图的数量没有完全填满一行,则 hist 会中断。例如:pd.Series(randn(1000)).hist(by=randint(0, 5, 1000), sharex=True, sharey=True)我已经打开了一个问题:github.com/pydata/pandas/issues/8256
    猜你喜欢
    • 1970-01-01
    • 2016-07-24
    • 2023-04-09
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    相关资源
    最近更新 更多