Matplotlib sharex on data with different x values?

With matplotlib alone, this can be done by combining the two dataframes:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

fig, axes = plt.subplots(2, sharex='all')

ax1, ax2 = axes

df = pd.DataFrame({'x': ['A', 'B', 'C', 'D', 'E', 'F'], 'y1': np.arange(6)})
df2 = pd.DataFrame({'x': ['B', 'D', 'E'], 'y2': np.random.rand(3)})

combined = df.merge(df2, how='left', on='x')

ax1.bar(combined['x'], combined['y1'])
ax2.bar(combined['x'], combined['y2'])

enter image description here


Seaborn's order argument can take a list which can contain values that are not in the data. So you can supply the unique values from the x columns.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame({'x':['A','B','C','D','E','F'],'y1':np.random.rand(6)})
df2 = pd.DataFrame({'x':['B','D','E'],'y2':np.random.rand(3)})

order = np.unique(list(df.x)+list(df2.x))

fig,axes = plt.subplots(2, sharex='all')

sns.barplot(x='x',y='y1',data=df,ax=axes[0], order=order)
sns.barplot(x='x',y='y2',data=df2,ax=axes[1], order=order)

plt.show()

enter image description here