Mattia Surricchio
Mattia Surricchio

Reputation: 1608

Seaborn align plots in subplots

I'm using Seaborn to plot 3 ghaphs. I would like to know how could I align vertically different plots.

This is my plot so far:

enter image description here

And this is my code:

import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.ticker as plticker
import seaborn as sns
import numpy as np

flatui = ["#636EFA", "#EF553B", "#00CC96", "#AB63FA"]

fig, ax = plt.subplots(figsize=(17, 7))    
plot=sns.lineplot(ax=ax,x="number of weeks", y="avg streams", hue="year", data=df, palette=flatui)

ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:,.2f}'.format(x/1000) + 'K'))

plot.set(title='Streams trend')
plot.xaxis.set_major_locator(ticker.MultipleLocator(2))

    

    
fig, ax =plt.subplots(1,2, figsize=(17,7))
plot = sns.barplot(x="Artist", y="Releases", data = result.head(10), ax=ax[0])
plot.set_xticklabels(
    plot.get_xticklabels(), 
    rotation=90, 
    horizontalalignment='center',
    fontweight='light',
    fontsize='x-large'

)
plot=sns.barplot(x="Artist", y="Streams", data = result.head(10), ax=ax[1])
plot.set_xticklabels(
    plot.get_xticklabels(), 
    rotation=90, 
    horizontalalignment='center',
    fontweight='light',
    fontsize='x-large'

)

Basically I create a figure where I plot the trend graph and then a figure with 2 subplots where I plot my 2 bar plots.

What I would like to do is to align the trend plot and the 2 barplots. As you might notice on the left, the trend plot and the first barplot are not aligned, I would like to make the two figures start from the same point (like at the ending of the trend plot and the second barplot, where the 2 graphs are aligned).

How could I do that?

Upvotes: 0

Views: 2492

Answers (1)

Diziet Asahi
Diziet Asahi

Reputation: 40667

Here is a solution using GridSpec

fig = plt.figure()
gs0 = matplotlib.gridspec.GridSpec(2,2, figure=fig)

ax1 = fig.add_subplot(gs0[0,:])
ax2 = fig.add_subplot(gs0[1,0])
ax3 = fig.add_subplot(gs0[1,1])

sns.lineplot(ax=ax1, ...)
sns.barplot(ax=ax2, ...)
sns.barplot(ax=ax3, ...)

If you have the newest version of matplotlib, you can also use the new semantic figure composition engine

axd = plt.figure(constrained_layout=True).subplot_mosaic(
    """
    AA
    BC
    """
)

sns.lineplot(ax=axd['A'], ...)
sns.barplot(ax=axd['B'], ...)
sns.barplot(ax=axd['C'], ...)

Upvotes: 2

Related Questions