Save multiple figures in one pdf page, matplotlib - python

I'm trying to get my figures in just one pdf page, but I don't know how to do this. I found out that it's possible to save multiple figures in a pdf file with 'matplotlib.backends.backend_pdf', but it doesn't work for just one page.
Has anyone any ideas ? Convert the figures to just one figure ?

You can use matplotlib gridspec to have multiple plots in 1 window
http://matplotlib.org/users/gridspec.html
from matplotlib.gridspec import GridSpec
import random
import numpy
from matplotlib import pyplot as pl
fig = pl.figure(figsize=(12, 16))
G = GridSpec(2,2)
axes_1 = pl.subplot(G[0, :])
x = [random.gauss(3,1) for _ in range(400)]
bins = numpy.linspace(-10, 10, 100)
axes_1.hist(x, bins, alpha=0.5, label='x')
axes_2 = pl.subplot(G[1, :])
axes_2.plot(x)
pl.tight_layout()
pl.show()
You can change the rows and column values and can subdivide the sections.

The PDF backend makes one page per figure. Use subplots to get multiple plots into one figure and they'll all show up together on one page of the PDF.

Here is a solution provided by matplotlib:
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
with PdfPages('foo.pdf') as pdf:
#As many times as you like, create a figure fig and save it:
fig = plt.figure()
pdf.savefig(fig)
....
fig = plt.figure()
pdf.savefig(fig)
VoilĂ 
Find a full example here: multipage pdf matplotlib
And by the way, for one figure, you don't need matplotlib.backends.backend_pdf just add pdf extension like so:
plt.savefig("foo.pdf")

Related

How can I output function results to pdf in Jupyter Notebook

I am working in Jupyter Notebook and I have a function that generates multiple plots upon being called. I want to directly save all plots from this function call under one pdf. Is there ways to do that?
Any help will be much appreciated!
Alison
You can use PDFPages to save all of your plots into a pdf. You can try the following example and implement it similarly in your code:
You can create a plotGraph function:
def plotGraph(X,Y):
fig = plt.figure()
### Plotting code ###
return fig
Then use that to get your and place them in your pdf.
from matplotlib.backends.backend_pdf import PdfPages
plot1 = plotGraph(graph1, label1)
plot2 = plotGraph(graph2, label2)
plot3 = plotGraph(graph3, label3)
pp = PdfPages('foo.pdf')
pp.savefig(plot1)
pp.savefig(plot2)
pp.savefig(plot3)
pp.close()
If you are okay with saving it as a PNG file with all the plots you can try the following:
from matplotlib import pyplot as plt
fig = plt.figure()
axis1 = fig.add_subplot(211)
axis1.plot(range(10))
axis2 = fig.add_subplot(212)
axis2.plot(range(10,20))
fig.savefig('allplots.png')
This basically creates subplots and saves all your plots in 1 png file.

How to Create a Real-Time Color Map in Python?

I am trying to create a real-time colour map. I want to continuously change slightly the RGB values of some elements in the matrix to make up my colour map. I read data from an excel file and a part of my data looks like this
Then I want to show the colour change in my colour map in one figure like a video. I tried this code:
df=pd.read_excel(r"G:\3Y_individualProject\Crop_color_data.xlsx", usecols="C:E")
color_data_2d=np.array(df.iloc[0:101])
color_data_1d=np.reshape(color_data_2d,(300))
color_data=color_data_1d.reshape(5,20,3)
for x in range(5):
fig, ax = plt.subplots()
ax.imshow(color_data)
ax.set_aspect("equal")
plt.pause(0.05)
for i in range(3):
color_data[0,1,i]=color_data[0,1,i]+0.1
color_data[1,1,i]=color_data[1,1,i]+0.2
color_data[2,1,i]=color_data[1,1,i]+0.25
print(color_data)
But it plots many different figures instead of showing them in a figure as I expected. I've also just tried to learn and use matplotlib.animation. I have tried the code below:
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
from matplotlib import cm
from matplotlib.animation import FuncAnimation
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
import itertools
def changeColor(x):
fig, ax = plt.subplots()
ax.imshow(color_data)
ax.set_aspect("equal")
for i in range(3):
color_data[0,1,i]=color_data[0,1,i]+0.1
color_data[1,1,i]=color_data[1,1,i]+0.2
color_data[2,1,i]=color_data[1,1,i]+0.25
results=FuncAnimation(plt.gcf(), changeColor, interval=5)
plt.tight_layout()
plt.show()
But with that code, my figure doesn't even display anything. As said I am quite new to matplotlib.animation so can anyone show me how to use matplotlib.animation or any other way to plot a real-time color map in my case, please? Thank you so much!

How to add multiple histograms in a figure using Matplotlib?

I'm using matplotlib to plot many histograms in one plot successfully:
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(1)
for i in range(0, 6):
data = np.random.normal(size=1000)
plt.hist(data, bins=30, alpha = 0.5)
plt.show()
However, I wish to export this plot in a pdf, using PdfPages. I want to add each histogram in a separate page, which I successfully do like this:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
np.random.seed(1)
fig = []
with PdfPages("exported_data.pdf") as pdf:
for i in range(0, 6):
data = np.random.normal(size=1000)
fig.append(plt.hist(data, bins=30, alpha = 0.5))
pdf.savefig(fig[i])
plt.close()
But I want another, 7th page with all the plots in one figure as shown above. How do I add many histograms in the same figure (so I can then add in the pdf page)? I see many tutorials on how to plot a grid of histograms within a figure but I haven't found one with all the histograms in one plot added to a figure.
Thanks,
Stam
You can run the loop to plot all histograms together (your first code snippet) after having run the loop to plot them separately (your second code snippet). Here is an example where the random arrays are saved in the datasets list during the first loop to be able to plot them together in the second loop. This solution works by using plt.gcf() which returns the current figure.
import numpy as np # v 1.19.2
import matplotlib.pyplot as plt # v 3.3.4
from matplotlib.backends.backend_pdf import PdfPages
np.random.seed(1)
datasets = []
with PdfPages("exported_data.pdf") as pdf:
# Plot each histogram, adding each figure to the pdf
for i in range(6):
datasets.append(np.random.normal(size=1000))
plt.hist(datasets[i], bins=30, alpha = 0.5)
pdf.savefig(plt.gcf())
plt.close()
# Plot histograms together using a loop then add the completed figure to the pdf
for data in datasets:
plt.hist(data, bins=30, alpha = 0.5)
pdf.savefig(plt.gcf())
plt.close()

save multiple histograms in folder from a python code

I have a loop to generate millions of histograms in python and i need to store them all in one folder in my laptop is there a way to save them all without the need of pressing save button each time a histogram generated?
Thanks
If you're using matplotlib, then what you are looking for is plt.savefig(). The documentation is here: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig
For example:
import matplotlib.pyplot as plt
import numpy as np
# Some random data:
x = np.random.rand(100)
fig = plt.figure(1) # create a figure instance
ax = fig.add_subplot(111) # and axes
ax.hist(x) # plot the histogram
# plt.show() # this would show the plot, but you can leave it out
# Save the figure to the current path
fig.savefig('test_image.png')

How to show multiple images in one figure?

I use Python lib matplotlib to plot functions, and I know how to plot several functions in different subplots in one figure, like this one,
And when handling images, I use imshow() to plot images, but how to plot multiple images together in different subplots with one figure?
The documentation provides an example (about three quarters of the way down the page):
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
fig = plt.figure()
a=fig.add_subplot(1,2,1)
img = mpimg.imread('../_static/stinkbug.png')
lum_img = img[:,:,0]
imgplot = plt.imshow(lum_img)
a.set_title('Before')
plt.colorbar(ticks=[0.1,0.3,0.5,0.7], orientation ='horizontal')
a=fig.add_subplot(1,2,2)
imgplot = plt.imshow(lum_img)
imgplot.set_clim(0.0,0.7)
a.set_title('After')
plt.colorbar(ticks=[0.1,0.3,0.5,0.7], orientation='horizontal')
# ---------------------------------------
# if needed inside the application logic, uncomment to show the images
# plt.show()
Basically, it's the same as you do normally with creating axes with fig.add_subplot...
Simple python code to plot subplots in a figure;
rows=2
cols=3
fig, axes = plt.subplots(rows,cols,figsize=(30,10))
plt.subplots_adjust(wspace=0.1,hspace=0.2)
features=['INDUS','RM', 'AGE', 'DIS','PTRATIO','MEDV']
plotnum=1
for idx in features:
plt.subplot(rows,cols,plotnum)
sns.distplot(data[idx])
plotnum=plotnum+1
plt.savefig('subplots.png')
go through below link for more detail
https://exploredatalab.com/how-to-plot-multiple-subplots-in-python-with-matplotlib/

Categories

Resources