Skip to content

Instantly share code, notes, and snippets.

@dkapitan
Created July 26, 2018 09:50
Show Gist options
  • Save dkapitan/fcf45a97caaf48bc3d6be17b5f8b213c to your computer and use it in GitHub Desktop.
Save dkapitan/fcf45a97caaf48bc3d6be17b5f8b213c to your computer and use it in GitHub Desktop.
Multiple Seaborn plots in a grid
# https://stackoverflow.com/questions/35042255/how-to-plot-multiple-seaborn-jointplot-in-subplot
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import seaborn as sns
import numpy as np
class SeabornFig2Grid():
def __init__(self, seaborngrid, fig, subplot_spec):
self.fig = fig
self.sg = seaborngrid
self.subplot = subplot_spec
if (isinstance(self.sg, sns.axisgrid.FacetGrid) or isinstance(self.sg, sns.axisgrid.PairGrid)):
self._movegrid()
elif isinstance(self.sg, sns.axisgrid.JointGrid):
self._movejointgrid()
self._finalize()
def _movegrid(self):
""" Move PairGrid or Facetgrid """
self._resize()
n = self.sg.axes.shape[0]
m = self.sg.axes.shape[1]
self.subgrid = gridspec.GridSpecFromSubplotSpec(
n, m, subplot_spec=self.subplot)
for i in range(n):
for j in range(m):
self._moveaxes(self.sg.axes[i, j], self.subgrid[i, j])
def _movejointgrid(self):
""" Move Jointgrid """
h = self.sg.ax_joint.get_position().height
h2 = self.sg.ax_marg_x.get_position().height
r = int(np.round(h / h2))
self._resize()
self.subgrid = (gridspec.GridSpecFromSubplotSpec(r + 1, r + 1,
subplot_spec=self.subplot))
self._moveaxes(self.sg.ax_joint, self.subgrid[1:, :-1])
self._moveaxes(self.sg.ax_marg_x, self.subgrid[0, :-1])
self._moveaxes(self.sg.ax_marg_y, self.subgrid[1:, -1])
def _moveaxes(self, ax, gs):
# https://stackoverflow.com/a/46906599/4124317
ax.remove()
ax.figure = self.fig
self.fig.axes.append(ax)
self.fig.add_axes(ax)
ax._subplotspec = gs
ax.set_position(gs.get_position(self.fig))
ax.set_subplotspec(gs)
def _finalize(self):
plt.close(self.sg.fig)
self.fig.canvas.mpl_connect("resize_event", self._resize)
self.fig.canvas.draw()
def _resize(self, evt=None):
self.sg.fig.set_size_inches(self.fig.get_size_inches())
@dkapitan
Copy link
Author

@WindyCatHub
you need to make sure that the downloaded file seabornfig2grid.py is located somewhere such that the python interpreter can find it. Putting it in the same directory as your notebook or script usually does the trick.

@WindyCatHub
Copy link

WindyCatHub commented Nov 27, 2020 via email

@WindyCatHub
Copy link

WindyCatHub commented Nov 27, 2020 via email

@dkapitan
Copy link
Author

Enjoy that blissful feeling of triumph, and move on to your next challenge ... 😄

@WindyCatHub
Copy link

WindyCatHub commented Nov 27, 2020 via email

@dkapitan
Copy link
Author

@WindyCatHub
It's hard for me to provide feedback without seeing your code. Perhaps the original SO post could help: https://stackoverflow.com/q/35042255/3197404

@dkapitan
Copy link
Author

My gist is quite old. Perhaps the new plotly library has exactly what you need: https://plotly.com/python/2d-histogram-contour/

@YuHuang3019
Copy link

Hi, thank you for sharing this solution! I am wondering how can we save the figure as a pdf file if using your function. When I tried to do fig.savefig('xxx.pdf'), I will lose the marginal distribution plots in the file. I think it is due to the fact that we removed some axes, making it very tricky. Would appreciate it if you can help to figure it out.

@dkapitan
Copy link
Author

Hi, thank you for sharing this solution! I am wondering how can we save the figure as a pdf file if using your function. When I tried to do fig.savefig('xxx.pdf'), I will lose the marginal distribution plots in the file. I think it is due to the fact that we removed some axes, making it very tricky. Would appreciate it if you can help to figure it out.

@YuHuang3019 a lot has changed in seaborne and I haven't used the pdf export myself.

As an alternative solution you could try Altair which is my current default plotting library:
https://iliatimofeev.github.io/altair-viz.github.io/gallery/scatter_marginal_hist.html

You can export Altair plots in different formats for downstream processing.

@YuHuang3019
Copy link

Hi, thank you for sharing this solution! I am wondering how can we save the figure as a pdf file if using your function. When I tried to do fig.savefig('xxx.pdf'), I will lose the marginal distribution plots in the file. I think it is due to the fact that we removed some axes, making it very tricky. Would appreciate it if you can help to figure it out.

@YuHuang3019 a lot has changed in seaborne and I haven't used the pdf export myself.

As an alternative solution you could try Altair which is my current default plotting library: https://iliatimofeev.github.io/altair-viz.github.io/gallery/scatter_marginal_hist.html

You can export Altair plots in different formats for downstream processing.

@dkapitan Hi Daniel, thank you so much for sharing this package with me. I just realized that I did plot out the marginal distributions but somehow the color and linewidth for the distributions are too light/small to show. I checked the pdf files on the browser before and I could not see the distribution plots. I later downloaded the file, zoomed in the pdf, and then I was able to figure this out. Sincerely thank you again for your quick response!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment