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:
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..
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.
Then execute the cell
Related
I am making some small tests in Jupyter. The user should see two plots, one on the left and one on the right. Than after clicking somewhere on the left plot something on the right plot should happen. For example here a click on the left plot will produce a red dot on the right plot in the same place:
%matplotlib notebook
def onclick(event):
ax.clear()
ax2.clear()
ax.set_xlim(0,10)
ax.set_ylim(0,10)
ax2.set_xlim(0,10)
ax2.set_ylim(0,10)
ax2.plot([event.xdata],[event.ydata],'o',color='red')
ax.figure.canvas.draw_idle()
ax2.figure.canvas.draw_idle()
fig = plt.figure(figsize=(20,10))
ax = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
ax.set_xlim(0,10)
ax.set_ylim(0,10)
ax2.set_xlim(0,10)
ax2.set_ylim(0,10)
cid = fig.canvas.mpl_connect('button_press_event',onclick)
This works, but the visualization in Jupyter is not the best. Is there a way to have this kind of interactive plots working outside of a Jupyter notebook ? Maybe in a window with varying dimensions ? As an example, how would one proceed with the example above ?
You can use plotly and export your plots to html file:
https://plotly.com/python/interactive-html-export/
I think I found a possible simple answer to my needs. Simply put the code in the question in a python script, remove the 'magic' command and insert at the end:
plt.show(block=True)
This way matplotlib will just use a different backend than notebook or inline in Jupiter and plot the figure in a separate window. This window is compatible with the interactive commands from matplotlib. I am not sure about widget compatibility though I will try and update the answer.
Update: I do not think ipywidgets can be used with plt.show() since these are not plotted in an axes, but there are some widgets within matplotlib (matplotlib.widgets) that can be used. Though, the resulting speed in my case is not satisfactory so I would avoid combining matplotlib widgets with matplotlib event catching.
I would like to plot two or more graphs at once using python and matplotlib. I do not want to use subplot since it is actually two or more plots on the same drawing paper.
Is there any way to do it?
You can use multiple figures and plot some data in each of them. The easiest way of doing so is to call plt.figure() and use the pyplot statemachine.
import matplotlib.pyplot as plt
plt.figure() # creates a figure
plt.plot([1,2,3])
plt.figure() # creates a new figure
plt.plot([3,2,1])
plt.show() # opens a window for each of the figures
If for whatever reason after creating a second figure you want to plot to the first one, you need to 'activate' it via
plt.figure(1)
plt.plot([2,3,1]) # this is plotted to the first figure.
(Figure numbers start at 1)
For a little jupyter notebook widget i tried the following:
with output:
fig, ax = plt.subplots(constrained_layout=True, figsize=(6, 4))
# move the toolbar to the bottom
fig.canvas.toolbar_position = 'bottom'
ax.grid(True)
line, = ax.plot(df.index, init_data, initial_color,)
ax.set_ylabel('CH4_HYD1')
ax.set_ylabel('')
But the data gets plotted in a wierd way. When isolating the plotting method and comparing it to the pandas default, the pandas plot displays the data correctly.
df['CH4_HYD1'].plot()
Pandas plot
plt.plot(['CH4_HYD1'])
Wrong plot?
I would like to use the axis plot method to produce a plot with multiple lines of different features. But I can't find the probably very simple error... What is the difference here?
This is a short example of how to plot multiple lines from a DataFrame with matplotlib and with pandas. Essentially, pandas uses matplotlib to do the plots so it shouldn't be different.
Anyway, I encourage you to look into seaborn. This is a great library based on pandas and matplotlib that enables visualizing dataframes easily.
I'm making something using Matplotlib where I have multiple subplots on a figure. It seems to me like the subplot API is limited compared to the PyPlot API: for example, I can't seem to make custom axes labels in my subplot although it is possible using PyPlot.
My question is: Is there a richer subplot API besides the tiny one on the PyPlot page (http://matplotlib.org/api/pyplot_api.html), and/or is there a way to get the full functionality of a PyPlot on a subplot?
Basically, what is a subplot? I can't find it in the documentation. Even more generally, when should I use a figure vs an axis vs a subplot? They all seem to do essentially the same thing.
Consider the following code:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(2,1,1)
Then ax is an axis? Can I use the pyplot API to customize ax?
Thanks for your help.
While i suggest that use the axes methods, there is the plt.sca function (set current axes).
So
plt.sca(ax)
does what you want, i think.
In general, I don't have any problem to put two plots in a figure like plot(a);plot(b) in matplotlib. Now I am using a particular library which would generate a figure and I want to overlay with boxplot. Both are generated by matplotlib. So I think it should be fine but I can only see one plot. Here is the code. I am using beeswarm and here is its ipython notebook. I can only plot beeswarm or boxplot but not both in a figure. My main goal is trying to save column scatter plot and boxplot together as a figure in pdf. Thanks,
from beeswarm import beeswarm
fig=plt.figure()
figure(figsize=(5,7))
ax1=plt.subplot(111)
fig.ylim=(0,11)
d2 = np.random.random_integers(10,size=100)
beeswarm(d2,col="red",method="swarm",ax=ax1,ylim=(0,11))
boxplot(d2)
The problem is with the positioning of the box plot. The default positioning list starts with 1 what shifts the plot to 1 and your beeswarm plot sits on 0.
So the plots are in different places of your canvas.
I modified your code a little bit and that seems to solve your problem.
from beeswarm import beeswarm
fig = plt.figure(figsize=(5,7))
ax1 = fig.add_subplot(111)
# Here you may want to use ax1.set_ylim(0,11) instead fig.ylim=(0,11)
ax1.set_ylim(0,11)
d2 = np.random.random_integers(10,size=100)
beeswarm(d2,col="red",method="swarm",ax=ax1,ylim=(0,11))
boxplot(d2,positions=[0])
Cheers