Home > Software engineering >  Make width of seaborn facets proportional to the range of data along the x axis
Make width of seaborn facets proportional to the range of data along the x axis

Time:10-21

I have used FacetGrid() from the seaborn module to break a line graph into segments with labels for each region as the title of each subplot. I saw the option in the documentation to have the x-axes be independent. However, I could not find anything related to having the plot sizes correspond to the size of each axis.

The code I used to generate this plot, along with the plot, are found below.

import matplotlib.pyplot as plt
import seaborn as sns

# Added during Edit 1.
sns.set()

graph = sns.FacetGrid(rmsf_crys, col = "Subunit", sharex = False)
graph.map(plt.plot, "Seq", "RMSF")
graph.set_titles(col_template = '{col_name}')

plt.show()

Plot resulting from the above code 1

Edit 1

Updated plot code using relplot() instead of calling FacetGrid() directly. The final result is the same graph.

import matplotlib.pyplot as plt
import seaborn as sns

# Forgot to include this in the original code snippet.
sns.set()

graph = sns.relplot(data = rmsf_crys, x = "Seq", y = "RMSF", 
                    col = "Subunit", kind = "line", 
                    facet_kws = dict(sharex=False))
graph.set_titles(col_template = '{col_name}')

plt.show()

CodePudding user response:

Full support for this would need to live at the matplotlib layer, and I don't believe it's currently possible to have independent axes but shared transforms. (Someone with deeper knowledge of the matplotlib scale internals may prove me wrong).

But you can get pretty close by calculating the x range you'll need ahead of time and using that to parameterize the gridspec for the facets:

import numpy as np, seaborn as sns
tips = sns.load_dataset("tips")
xranges = tips.groupby("size")["total_bill"].agg(np.ptp)
xranges *= 1.1  # Account for default margins
sns.relplot(
    data=tips, kind="line",
    x="total_bill", y="tip",
    col="size", col_order=xranges.index,
    height=3, aspect=.65,
    facet_kws=dict(sharex=False, gridspec_kws=dict(width_ratios=xranges))
)

enter image description here

  • Related