【问题标题】:Seaborn subpots - share x axis between line and bar chartSeaborn 子图 - 在折线图和条形图之间共享 x 轴
【发布时间】:2019-09-03 03:35:44
【问题描述】:

我正在尝试通过 Seaborn 在 Juyter 实验室笔记本中创建 2 个堆叠图表;其中一个是折线图,另一个是条形图。两者应共享相同的 x 轴。

%matplotlib widget

dt = pd.DataFrame.from_dict({'column_x': range(-10,10), 'vals_1': range(10,30), 'vals_2':range(30,50)})

f, axarr = plt.subplots(2, sharex=True)
sns.lineplot(x="column_x", y="vals_1", data=dt, marker="o", ax=axarr[0])
sns.barplot(x="column_x", y="vals_2", data=dt, ax=axarr[1])

问题是 - 这似乎实际上并不共享轴。我不完全确定为什么,我最好的选择是条形图将其 x 轴视为分类或此类。

有没有办法在两个图之间正确共享(数字)x 轴?

谢谢

【问题讨论】:

    标签: python matplotlib seaborn


    【解决方案1】:

    lineplot 是数字图,而barplot 是分类图。您可能希望将lineplot 替换为pointplot,这也是一个分类图。

    import pandas as pd
    import matplotlib.pyplot as plt
    import seaborn as sns
    
    
    dt = pd.DataFrame.from_dict({'column_x': range(-10,10), 'vals_1': range(10,30), 'vals_2':range(30,50)})
    
    f, axarr = plt.subplots(2, sharex=True)
    sns.pointplot(x="column_x", y="vals_1", data=dt, marker="o", ax=axarr[0])
    sns.barplot(x="column_x", y="vals_2", data=dt, ax=axarr[1])
    
    plt.show()
    

    【讨论】:

      【解决方案2】:

      您是对的,seaborn 在制作条形图时将 x 值视为分类:

      来自docs

      此函数始终将变量之一视为分类变量,并在相关轴上的序数位置 (0, 1, ... n) 绘制数据,即使数据具有数字或日期类型。

      所以,我认为最简单的方法可能是关闭sharex,然后自己滚动:

      axarr[0].set_xlim(dt['column_x'].min()-0.5, dt['column_x'].max()+0.5)
      axarr[0].xaxis.set_major_locator(ticker.MultipleLocator(1))
      

      应该使两个轴范围和刻度位置看起来相同

      【讨论】:

        猜你喜欢
        • 2021-05-12
        • 2019-05-01
        • 2019-02-03
        • 2020-07-17
        • 2021-01-31
        • 2020-03-06
        • 2019-06-25
        • 2019-12-07
        • 2021-03-14
        相关资源
        最近更新 更多