render two seaborn figure objects in same ipython cell - python

I have two matplotlib (seaborn) figure objects both made in different ipython cells.
#One Cell
fig_1_object = sns.factorplot(y='freq',x='d_fam',col='easy_donor',kind="bar",data=collection_d_fam)
fig_1 = fig_1_object.fig
#Two Cell
fig_2_object = sns.factorplot(y='freq',x='d_fam',col='easy_donor',kind="bar",data=collection_c_fam)
fig_2 = fig_2_object.fig
How can I "show" them one after another in the same cell. I have matplotlib inline turned on.
#third cell
fig_1
fig_2
>>Only shows fig_2

You can use plt.show() after each image:
sns.factorplot(y='freq',x='d_fam',col='easy_donor',kind="bar",data=collection_d_fam)
plt.show()
sns.factorplot(y='freq',x='d_fam',col='easy_donor',kind="bar",data=collection_c_fam)
plt.show()

You just need to import the display function from the IPython.display module:
from IPython.display import display
import seaborn
%matplotlib inline
g1 = seaborn.factorplot(**options1)
g2 = seaborn.factorplot(**options2)
display(g1)
display(g2)

What about this?
plt.figure(1, figsize=(5,10))
plt.subplot(211)
# Figure 1
sns.factorplot(y='freq',x='d_fam',col='easy_donor',kind="bar",data=collection_d_fam)
plt.subplot(212)
# Figure 2
sns.factorplot(y='freq',x='d_fam',col='easy_donor',kind="bar",data=collection_c_fam)

//For displaying 2 or more fig in the same row or columns :-
fig, axs = plt.subplots(ncols=2,nrows=2,figsize=(14,5))
//The above (ncols) take no of columns and (nrows) take no of rows and (figsize) to enlarge the image size.
sns.countplot(x=data['Rating'],palette="rocket",ax=axs[0][0])
sns.countplot(x=data['Rating'][0:50],palette="rocket",ax=axs[1][0])
sns.countplot(x=data['Rating'],palette="rocket",ax=axs[0][0])
sns.countplot(x=data['Rating'][0:50],palette="rocket",ax=axs[1][0])`
//Here in any plot u want to plot add **ax** and pass the position and you are ready !!!

Related

Set xticks visible in when plotting using pandas

Consider the following snippet
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
data = np.random.rand(10,5)
cols = ["a","b","c","d","e"]
df = pd.DataFrame(data=data, columns = cols)
df.index.name="Time (s)"
fig,axes = plt.subplots(3,2,sharex=True, squeeze=False)
axes = axes.T.flat
axes[5].remove()
df.plot(subplots=True,grid=True,legend=True,ax = axes[0:5])
that produces the following plot
I wish to show the xticks in the subplots where they are missing as I wrote in red with reference to the above picture.
I wish to show only the xticks where I marked in red, not the labels. The labels are fine where they currently are and shall be kept there.
After some search, I tried with
for ax in axes:
ax.tick_params(axis="x")
and
for ax in axes:
ax.spines.set(visible=True)
but with no success.
Any hints?
EDIT: As someone kindly suggested, if I set sharex=False, then when I horizontally zoom on one axes I will not have the same zoom effect on the other axes and this is not what I want.
What I want is to: a) show the xticks in all axes, b) when I horizontally zoom on one axes all the other axes are horizontally zoomed of the same amount.
You need to turn off sharing x properties by setting sharex=False (which is the default value by the way in matplotlib.pyplot.subplots):
Replace this:
fig,axes = plt.subplots(3,2,sharex=True, squeeze=False)
By this:
fig,axes = plt.subplots(3,2, squeeze=False)
# Output:

Show only the last plot in Python using MatPlotLib

I am using Python 3.5 with MatPlotLib package. My problem is as follows:
I generate, say 50 plots, which I save each to a PNG file. Then I generate 2 summarizing plots, which I want to both save and show on display. However, when I use the plt.show() command, it also shows all the previous 50 plots, which I don't want to display, just save them. How to suppress the show on these previous 50 plots and show only the last one?
Here is an example code:
import matplotlib.pyplot as plt
import numpy as np
for i in range(50):
fig = plt.figure()
plt.plot(np.arange(10),np.arange(10)) # just plot something
plt.savefig(f"plot_{i}.png")
# I want to save these plots but not show them
# summarizing plot
fig = plt.figure()
plt.plot(np.arange(100),np.arange(100))
plt.show() # now it shows this fig and the previous 50 figs, but I want only to show this one!
Close all after the loop:
plt.close("all") #this is the line to be added
fig = plt.figure()
plt.plot(np.arange(100),np.arange(100))
plt.show()

Jupyter: Replot in different cell

I'd like to do something like this:
import matplotlib.pyplot as plt
%matplotlib inline
fig1 = plt.figure(1)
plt.plot([1,2,3],[5,2,4])
plt.show()
In one cell, and then redraw the exact same plot in another cell, like so:
plt.figure(1) # attempting to reference the figure I created earlier...
# four things I've tried:
plt.show() # does nothing... :(
fig1.show() # throws warning about backend and does nothing
fig1.draw() # throws error about renderer
fig1.plot([1,2,3],[5,2,4]) # This also doesn't work (jupyter outputs some
# text saying matplotlib.figure.Figure at 0x..., changing the backend and
# using plot don't help with that either), but regardless in reality
# these plots have a lot going on and I'd like to recreate them
# without running all of the same commands over again.
I've messed around with some combinations of this stuff as well but nothing works.
This question is similar to IPython: How to show the same plot in different cells? but I'm not particularly looking to update my plot, I just want to redraw it.
I have found a solution to do this. The trick is to create a figure with an axis fig, ax = plt.subplots() and use the axis to plot. Then we can just call fig at the end of any other cell we want to replot the figure.
import matplotlib.pyplot as plt
import numpy as np
x_1 = np.linspace(-.5,3.3,50)
y_1 = x_1**2 - 2*x_1 + 1
fig, ax = plt.subplots()
plt.title('Reusing this figure', fontsize=20)
ax.plot(x_1, y_1)
ax.set_xlabel('x',fontsize=18)
ax.set_ylabel('y',fontsize=18, rotation=0, labelpad=10)
ax.legend(['Eq 1'])
ax.axis('equal');
This produces
Now we can add more things by using the ax object:
t = np.linspace(0,2*np.pi,100)
h, a = 2, 2
k, b = 2, 3
x_2 = h + a*np.cos(t)
y_2 = k + b*np.sin(t)
ax.plot(x_2,y_2)
ax.legend(['Eq 1', 'Eq 2'])
fig
Note how I just wrote fig in the last line, making the notebook output the figure once again.
I hope this helps!

Multiple pie charts using matplotlib

I'm trying to display two charts at the same time using matplotlib.
But I have to close one graph then only I can see the other graph.
Is there anyway to display both the graphs or more number of graphs at the same time.
Here is my code
num_pass=np.size(data[0::,1].astype(np.float))
num_survive=np.sum(data[0::,1].astype(np.float))
prop=num_survive/num_pass
num_dead=num_pass-num_survive
#print num_dead
labels='Dead','Survived'
sizes=[num_dead,num_survive]
colors=['darkorange','green']
mp.axis('equal')
mp.title('Titanic Survival Chart')
mp.pie(sizes, explode=(0.02,0), labels=labels,colors=colors,autopct='%1.1f%%', shadow=True, startangle=90)
mp.show()
women_only_stats = data[0::,4] == "female"
men_only_stats = data[0::,4] != "female"
# Using the index from above we select the females and males separately
women_onboard = data[women_only_stats,1].astype(np.float)
men_onboard = data[men_only_stats,1].astype(np.float)
labels='Men','Women'
sizes=[np.sum(women_onboard),np.sum(men_onboard)]
colors=['purple','red']
mp.axis('equal')
mp.title('People on board')
mp.pie(sizes, explode=(0.01,0), labels=labels,colors=colors,autopct='%1.1f%%', shadow=True, startangle=90)
mp.show()
How can I show both the graphs at the same time?
There are several ways to do this, and the simplest is to use multiple figure numbers. Simply tell matplotlib that you are working on separate figures, and then show them simultaneously:
import matplotlib.pyplot as plt
plt.figure(0)
# Create first chart here.
plt.figure(1)
# Create second chart here.
plt.show() #show all figures
In addition to Banana's answer, you could also plot them in different subplots within the same figure:
from matplotlib import pyplot as plt
import numpy as np
data1 = np.array([0.9, 0.1])
data2 = np.array([0.6, 0.4])
# create a figure with two subplots
fig, (ax1, ax2) = plt.subplots(1, 2)
# plot each pie chart in a separate subplot
ax1.pie(data1)
ax2.pie(data2)
plt.show()
Alternatively, you can put multiple pies on the same figure using subplots/multiple axes:
mp.subplot(211)
mp.pie(..)
mp.subplot(212)
mp.pie(...)
mp.show()
Yes. This answer of User:Banana worked for me.
I had 4 graphs and all 4 popped up as individual pie charts when I ran the plt.show() so I believe you can use as many figure numbers as you want.
plt.figure(0) # Create first chart here and specify all parameters below.
plt.figure(1) # Create second chart here and specify all parameters below.
plt.figure(3) # Create third chart here and specify all parameters below.
plt.figure(4) # Create fourth chart here and specify all parameters below.
plt.show() # show all figures.

Python matplotlib graph problem

import matplotlib
import matplotlib.pyplot as plt
import pylab as PL
matplotlib.rcParams['axes.unicode_minus'] = False
fig = plt.figure()
ax = fig.add_subplot(111)
PL.loglog(a, b,'o')
ax.set_title('Graph Example')
plt.show()
1) This displays the graph with points on the plot. Is there a way to join these points with a smooth curve.
2) I want to draw more than one plot in the same graph(i.e. for a different set of values of lists a and b) . How do I do that? I want to represent points of each graph with a different symbol(cross,square,circle) or color.
See #Ber's comment
Simply call PL.loglog multiple times.

Categories