Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib sharex on data with different x values?

How can I modify the code below so that the plot spans all 6 x-axis values, and just has blank spots at A, C, F for df2's bars?

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

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

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

enter image description here

like image 266
pyjamas Avatar asked Apr 11 '19 22:04

pyjamas


2 Answers

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

like image 82
ImportanceOfBeingErnest Avatar answered Oct 25 '22 19:10

ImportanceOfBeingErnest


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

like image 44
gmds Avatar answered Oct 25 '22 19:10

gmds