【问题标题】:Matplotlib - missing some ticks when sharing an axis between subplotsMatplotlib - 在子图之间共享轴时缺少一些刻度
【发布时间】:2017-01-18 10:18:59
【问题描述】:

我正在尝试制作一个由 2 个具有共享 y 轴的子图组成的图形,但是缺少一些“刻度”。一个例子:

import matplotlib.pyplot as plt
import pandas as pd

df_a = pd.DataFrame({"Foo" : pd.Series(['A','B','C']), "Bar" : pd.Series([1,2,3])})
df_b = pd.DataFrame({"Foo" : pd.Series(['B','C','D']), "Bar" : pd.Series([4,5,6])})

fig, axes = plt.subplots(nrows=1, ncols=2, sharex= True, sharey=True)

df_a.plot.barh("Foo", "Bar", ax=axes[0], legend=False, title="df_a")
df_b.plot.barh("Foo", "Bar", ax=axes[1], legend=False, title="df_b")

生成下面的图(刻度标签混淆了):

我期待看到的是这样的(使用 R 生成):

我在这里错过了什么?

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    您需要相同的索引,因此一种可能的解决方案是concat

    df = pd.concat([df_a.set_index('Foo'), df_b.set_index('Foo')], axis=1)
    df.columns = ['a','b']
    print (df)
         a    b
    A  1.0  NaN
    B  2.0  4.0
    C  3.0  5.0
    D  NaN  6.0
    
    df.a.plot.barh(ax=axes[0], legend=False, title="df_a")
    df.b.plot.barh(ax=axes[1], legend=False, title="df_b")
    

    另一种解决方案是set_indexreindex by union of indexes

    df_a = df_a.set_index('Foo')
    df_b = df_b.set_index('Foo')
    df_a = df_a.reindex(df_a.index.union(df_b.index))
    df_b = df_b.reindex(df_a.index.union(df_b.index))
    print (df_a)
         Bar
    Foo     
    A    1.0
    B    2.0
    C    3.0
    D    NaN
    
    print (df_b)
         Bar
    Foo     
    A    NaN
    B    4.0
    C    5.0
    D    6.0
    
    
    
    df_a.plot.barh( ax=axes[0], legend=False, title="df_a")
    df_b.plot.barh( ax=axes[1], legend=False, title="df_b")
    

    【讨论】:

    • pd.concat 技巧就像一个魅力,非常适合我的其他工作流程。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-06
    • 2019-02-03
    • 1970-01-01
    • 2020-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多