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])
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()
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'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With