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()
Related
I have a dataframe v with some numerical data in it.
v=pd.DataFrame(data=np.random.rand(300,3))
I am want to plot on the same matplotlib figure:
a scatter plot
a moving average of the same points
I do that using pd.DataFrame.plot()
plt.figure()
v.plot(style='o',legend=False,ax=plt.gca(),alpha=0.2,ls='')
v.rolling(7).mean().plot(legend=False,ax=plt.gca())
This works fine.
However, the points drawn with the first plot are colored according to their row number. Same happens for the lines in the second plot.
I would like the two colors to be consistent between the two plot commands, so
line obtained by moving average to have same color as in the scatter. How to get that?
Here is what I get running the code.
Obviously, I cannot figure out if the red lines correspond to the green orange or blue points...
ORIGINAL
I believe you need -
%matplotlib inline # only for jupyter notebooks
import pandas as pd
from matplotlib import pyplot as plt
import numpy as np
colors = {0: 'red', 1:'green', 2:'blue'}
v=pd.DataFrame(data=np.random.rand(300,3))
plt.figure()
v.plot(marker='o',legend=False,ax=plt.gca(),ls='', alpha=0.2, color=colors.values())
v.rolling(7).mean().plot(legend=False,ax=plt.gca(), color=colors.values())
UPDATE
Just go with -
Option 1 (no extra cm dependency)
colors_rand = np.random.rand(len(v.columns),3)
v.plot(marker='o',legend=False,ax=plt.gca(),ls='', alpha=0.5, color=colors_rand )
v.rolling(7).mean().plot(legend=False,ax=plt.gca(), color=colors_rand )
Option 2(as suggested by OP)
v.plot(marker='o',legend=False,ax=plt.gca(),ls='', alpha=0.5, colors=cm.rainbow(np.linspace(0,1,v.shape[1]) ))
v.rolling(7).mean().plot(legend=False,ax=plt.gca(), colors=cm.rainbow(np.linspace(0,1,v.shape[1]) ))
I am trying to create a number (>100) subplots for later analysis. A grid up to 5x5 seems to work fine, any larger than that and the y-axis begins to get very squashed and the whole thing is unreadable. I have tried various different things, like setting aspect etc, but to no avail.
Here is the output for a 5x50 grid:
squashed subplots
and here is my code:
from matplotlib.backends.backend_pdf import PdfPages
pp = PdfPages('./output.pdf')
num_investigate = len(investigate)
ncols = 5
nrows = 50#math.ceil(num_investigate/ncols)
fig, axs = plt.subplots(nrows=nrows, ncols=ncols, sharex=False, figsize=(15,15))
for ax, file in zip(axs.flat, investigate[:(ncols*nrows)]):
try:
df = get_df_from_csv(file)
df['perf'] = df['val'] / df['val'].ix[0] - 1
#ax.set_ylim(bottom=df['perf'].min(), top=df['perf'].max())
ax.set_aspect('auto')
df['perf'].plot(ax=ax, title=file)
except:
pass
plt.tight_layout()
pp.savefig()
pp.close()
I'm at a real loss of how to solve this after much research.
How do I ensure that the each subplot size is constant and the output goes to more than one pdf page?
thanks
PdfPages saves one matplotlib figure to one page. A second calls to the savefig command will lead to the creation of a second page. Hence, if you want a second page in the output pdf, you need to create a second figure.
E.g. you can produce the first figure with a 5x5 grid and put the first 25 plots in that figure, then save it. Then create the next figure, add the next 25 plots to it and save it again.
There is a multipage_pdf example on the matplotlib page.
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 !!!
Normally if you plot two different figures using the default settings in pyplot, they will be exactly the same size, and if saved can be neatly aligned in PowerPoint or the like. I'd like to generate one figure, however, which has a legend outside of the figure. The script I'm using is shown below.
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(0,1,201)
y1=x**2
y2=np.sin(x)
fig1=plt.figure(1)
plt.plot(x,y1,label='y1')
handles1,labels1=plt.gca().get_legend_handles_labels()
lgd1=plt.gca().legend(handles1,labels1,bbox_to_anchor=(1.27,1),borderaxespad=0.)
fig2=plt.figure(2)
plt.plot(x,y2)
fig1.savefig('fig1',bbox_extra_artists=(lgd1,),bbox_inches='tight')
fig2.savefig('fig2')
plt.show()
The problem is that in PowerPoint, I can no longer align the two figures left and have their axes aligned. Due to the use of the 'extra artists' and 'bbox_inches=tight' arguments for the first figure, the width of its margins becomes different from the second figure.
Is there any way to 'transfer' the clip box from the first figure to the second figure, such that they can be aligned by 'align left' in PowerPoint?
I think an easier way to achieve what you want is to just construct one figure with two subplots, and let matplotlib align everything for you.
Do you think doing something like this is a good idea?
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(0,1,201)
y1=x**2
y2=np.sin(x)
fig = plt.figure()
a = fig.add_subplot(211)
a.plot(x,y1, label='y1')
lgd1 = a.legend(bbox_to_anchor = (1.27,1), borderaxespad=0.)
a = fig.add_subplot(212)
a.plot(x,y2)
fig.savefig('fig',bbox_extra_artists=(lgd1,),bbox_inches='tight')
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.