2

I'm trying to make a figure consisting of 2 subplots with a shared y axis, however some 'ticks' are missing. An example:

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

produces the plot below (tick labels are mixed up):

enter image description here

What I was expecting to see is something like this (produced using R):

enter image description here

What am I missing here?

1 Answer 1

1

You need same indexes, so one possible solution is 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")

Another solution is set_index and reindex 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")
Sign up to request clarification or add additional context in comments.

1 Comment

The pd.concat trick works like a charm and fits nicely with the rest of my workflow. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.