Skip to main content
 首页 » 编程设计

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

2025年02月15日19lonelyxmas

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

我在这里错过了什么?

请您参考如下方法:

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