Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display two figures, side by side, in a Jupyter cell

import pandas as pd
import seaborn as sns

# load data
df = sns.load_dataset('penguins', cache=False)

sns.scatterplot(data=df, x='bill_length_mm', y='bill_depth_mm', hue='sex')
plt.show()
sns.scatterplot(data=df, x='flipper_length_mm', y='body_mass_g', hue='sex')
plt.show()

When I draw two plots with seaborn, in one cell, in jupyter, I get this view:

enter image description here

I want to draw the plots, side by side, like this:

plot1 plot2

How I should do this?

Updated:

Not two plots on one figure, but two plots on two separate figures.

  • This is not the solution being sought, because it's two plots on one figure.
fig, ax = plt.subplots(1,2)
sns.plotType(someData, ax=ax[0])  # plot1
sns.plotType(someData, ax=ax[1])  # plot2
fig.show()
  • The solutions from the proposed duplicate ipython notebook arrange plots horizontally, do not work
    • The option with %html causes the figures to plot on top of each other
    • Additionally, other options were for ipython, not Jupyter, or recommended creating subplots..
like image 772
dasfex Avatar asked Oct 04 '20 19:10

dasfex


1 Answers

  • This is probably the simplest solution. Other solutions would likely involve hacking the backend environment of Jupyter.
  • This question is about displaying two figures, side by side.
    • Two separate figures, side by side, executed from a code cell, does not work.
  • You will need to create the separate figures, and the use plt.savefig('file.jpg') to save each figure to a file.
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# load data
df = sns.load_dataset('penguins', cache=False)

# create and save figure
sns.scatterplot(data=df, x='bill_length_mm', y='bill_depth_mm', hue='sex')
plt.savefig('bill.jpg')
plt.close()  # prevents figure from being displayed when code cell is executed

# create and save new figure
sns.scatterplot(data=df, x='flipper_length_mm', y='body_mass_g', hue='sex')
plt.savefig('flipper.jpg')
plt.close()  # prevents figure from being displayed when code cell is executed
  • Once the figures are saved to a file, they can be displayed side by side, by loading them in a markdown cell.
    • If the images are to large, the second figure will go to a new line.

enter image description here

  • Then execute the cell

enter image description here

like image 115
Trenton McKinney Avatar answered Oct 12 '22 21:10

Trenton McKinney