gpt4 book ai didi

python - Matplotlib - 在子图之间共享轴时缺少一些刻度

转载 作者:太空宇宙 更新时间:2023-11-04 05:15:48 25 4
gpt4 key购买 nike

我正在尝试制作一个由 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")

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

enter image description here

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

enter image description here

我在这里错过了什么?

最佳答案

您需要相同的索引,因此一种可能的解决方案是 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通过 union 索引:

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")

关于python - Matplotlib - 在子图之间共享轴时缺少一些刻度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41716709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com