matplotlib setting pdf raster resolution using pdfpages savefig dpi - python

I have a project that generates a set of charts using matplotlib and exports each one as an individual PNG file. The client also wants the group of charts output as a single PDF file. We have successfully got this to work using PIL Image and matplotlib PdfPages to import each PNG on a separate page and export the multi-page PDF, but the PDF output quality is unacceptable. If I use anything other than dpi=100 with savefig, then output is blank. Any suggestions on how to export a PDF with higher raster resolution?
pp = PdfPages(filepath+'Treatment Zone Charts.pdf')
for file in os.listdir(filepath):
if "Treatment Zone Charts" in file and file.endswith(".png"):
print filepath+file
#read PNG image
im = Image.open(filepath+'/'+file)
im = im.resize((1100,850),Image.ANTIALIAS)
im = np.array(im).astype(np.float) / 255
# Create a figure with size w,h tuple in inches
fig = Figure(figsize=(11,8.5))
# Create a canvas and add the figure to it.
canvas = PDF_FigureCanvas(fig)
#add image to plot
fig.figimage(im, 0, -220, zorder = 1)
# Save the Plot to the PDF file
pp.savefig(fig, dpi=100)
#close the PDF file after the last plot is created
pp.close()

The output was blank because the image was positioned off of the canvas. For dpi=200 and no resizing of the original image, we needed to modify figimage to:
fig.figimage(im, 0, -1080, zorder = 1)
The output is very sensitive to the y-value, a small change from -1080 and the image was placed off the top or bottom of the page. I don't understand why the dpi setting has this effect on the figimage y parameter, but this now produces PDF output with good quality.

Related

Plot a Point on an high resolution Image

I want to automate one process, and I need to place some kind of pointer on my image. I found a great solution which works exactly as I would like, but its disadvantage is that it destroys my picture quality. I want to keep same size of the build in picture.
Bellow I share my code and error, which I receive. I would be grateful for your help :)
from matplotlib import image
from matplotlib import pyplot as plt
from PIL import Image
# to read the image stored in the working directory
# data = image.imread(file_name)
data = Image.open('File_name')
x, y = data.size
# to draw a point on co-ordinate (200,300)
plt.figure(figsize=(x, y))
plt.plot(650, 310, marker='*', color="red")
# plt.axis('off')
plt.imshow(data)
File = "File_name"
plt.savefig(File)
plt.show()
ValueError: Image size of 105480x55224 pixels is too large. It must be less than 2^16 in each direction.

Convert 3D .stl file to JPG image with Python

How do I convert a 3D object in any STL file into a JPG or PNG image.
I tried searching a little bit online but I wasn't been able to arrive at finding any possible solutions.
Can anyone help me with the code that can do this straight forward task with Python? IS there any libraries that can help with that?
EDIT :
Code Sample:
from mpl_toolkits import mplot3d
from matplotlib import pyplot
import pathlib
DIR = str(pathlib.Path(__file__).parent.resolve()).replace('\\', '/')
path = f'{DIR}/any_stl_file.stl'
# Create a new plot
figure = pyplot.figure()
axes = mplot3d.Axes3D(figure)
# Load the STL files and add the vectors to the plot
your_mesh = mesh.Mesh.from_file(path)
axes.add_collection3d(mplot3d.art3d.Poly3DCollection(your_mesh.vectors))
# Auto scale to the mesh size
scale = your_mesh.points.flatten()
axes.auto_scale_xyz(scale, scale, scale)
pyplot.savefig(f"{DIR}/the_image.jpg")```
Take a look at https://pypi.org/project/numpy-stl/
This code snippet is from the link above:
from stl import mesh
from mpl_toolkits import mplot3d
from matplotlib import pyplot
# Create a new plot
figure = pyplot.figure()
axes = mplot3d.Axes3D(figure)
# Load the STL files and add the vectors to the plot
your_mesh = mesh.Mesh.from_file('tests/stl_binary/HalfDonut.stl')
axes.add_collection3d(mplot3d.art3d.Poly3DCollection(your_mesh.vectors))
# Auto scale to the mesh size
scale = your_mesh.points.flatten()
axes.auto_scale_xyz(scale, scale, scale)
# Show the plot to the screen
pyplot.show()
To save a pyplot object as an image:
pyplot.savefig("file_name.jpg")

how to save image in PLT

I'm trying to save my result image using matplotlib.pyplot as the following code which works good without any problem
import matplotlib.pyplot as plt
I = image.astype(np.uint8)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(I)
plt.plot(marker_x, marker_y, color='yellow')# our circle
ax.set_title('Macula')
plt.savefig("J://uni//final project//res_image//marked_M.png")
fig.show()
here is my saved picture plt.savefig("J://uni//final project//res_image//marked_M.png") :
the yellow circle is a plot and as you know when we use plt.plot automatically we have a white space around the main picture (sth like margin as you see in the picture ) and also the axes
and its my 'tkinter' UI:
I'm wondering if is any way to crop this annoying white space or save image in another way that we get rid of this margin?
You can use the matplotlib transparent flag
plt.savefig("J://uni//final project//res_image//marked_M.png", transparent=True)
This will save the image as a png file with a transparent background

Save matplotlib to final given size including titles [duplicate]

This question already has answers here:
How to adjust padding with cutoff or overlapping labels
(8 answers)
Closed 4 years ago.
I am making figures for publication. I need the final figure, including the titles and text to be 3 inches wide and saved as a .tiff file. I know I can specify the size of the plot via matplotlib using
matplotlib.pyplot.figure(figsize=(3,2), dpi=300)
However this only specifies the size of the actual plot, not including the titles and everything. Also, the titles get cut off of my saved .tiff file when I try this method. Of course the easy fix is to decrease the size of the plot and manually make the figure the correct size, but does anyone know of an automatic way to make the plot be a given final size with all the bells and whistles included?
Here is the output image which is saved (this one is a png so it can upload to stackoverflow). Note the plot titles are cut off for some reason.
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from PIL import Image
from io import BytesIO
bent=[2.83263904,2.75860489,2.64546045,2.4949913,2.34923737,2.16430217,2.02562783,1.82478841,1.70324689,1.70315642,1.39739535,1.33945747,1.22295623,1.15726486,1.08449954,0.96155077,0.90325786,0.84547091]
bent=[i/27 for i in bent]
print(bent)
planar=[4.11233905,3.93027011,3.65135645,3.38525615,3.1130921,2.81042899,2.58995789,2.36159934,2.15981447,1.9964454,1.74375941,1.63263452,1.48503205,1.38596544,1.26501988,1.17391638,1.07490417,0.99369748]
planar=[i/27 for i in planar]
bi=[2.51027966,2.56495852,2.47033072,2.33008642,2.19395126,2.13732249,1.80922673,1.76037446,1.52930137,1.56732451,1.33905847,1.24952153,1.15699233,1.08251496,0.98449116,0.93838164,0.86542147,0.725736]
bi=[i/34 for i in bi]
T=[3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
arr=[bi,bent,planar]
arr=np.array(arr)
arr=arr.T
font = {'family' : 'normal',
'weight' : 'normal',
'size' : 8}
matplotlib.rc('font', **font)
fig = plt.figure(figsize=(3,2), dpi=300)
plt.title("-ΔS$_m$ vs T") #for Fe$_4$Gd
plt.xlabel('Temperature (K)')
plt.ylabel("$-ΔS_m$ ($J.K^{-1}.mol^{-1}n (e^{-})^{-1}$)")
MMM=('Fe$_4$Gd$_2$','Fe$_4$Gd bent','Fe$_4$Gd planar')
plt.plot(T,arr,'o')
plt.legend(MMM, loc='best')
# save figure
# (1) save the image in memory in PNG format
png1 = BytesIO()
fig.savefig(png1, format='png')
# (2) load this image into PIL
png2 = Image.open(png1)
# (3) save as TIFF
png2.save('TESTTESTTEST.tiff')
png1.close()
Use plt.tight_layout(). You can find more details here.

Custom Artist In Matplotlib Legend

I have a program using PtQt that utilizes matplotlib to do some plot rendering. For saving images, I would like to make use of the legend to render a custom image (additionally the built-in draggable feature makes this very appealing). I'm reading up on the legend, but I can't seem to figure out how to make a legend that calls my own paintEvent() method for Qt in which I can render custom images.
In case this approach is terrible, here's my goal: I want to put a image (rendered inside the program by Qt) either inside the plot window or find a way to append this image on top of the exported figure.
Here's a screenshot of what the output looks like now:
I'd like to take the DAIP... sequence at the top and have that exported with the figure.
Hopefully someone has tackled a similar problem before.
I solved it by using the OffsetImage and AnnotationBBox features of matplotlib after saving the image to a temporary png file. For some reason keeping it as a temporary file didn't work well.
Briefly:
#draw stuff onto QPixmap named pix
byteArray = QByteArray()
buffer = QBuffer(byteArray)
buffer.open(QIODevice.WriteOnly)
pix.save(buffer, 'PNG')
stringIO = StringIO(byteArray)
stringIO.seek(0)
tfile = tempfile.NamedTemporaryFile(suffix=".png", mode="wb", delete=False)
tfile.write(stringIO.buf)
tfile.close()
imagebox = mpl.offsetbox.OffsetImage(mpl._png.read_png(tfile.name),zoom=zlvl)
ab = mpl.offsetbox.AnnotationBbox(imagebox, [w/2,0],frameon=False)
ab.set_figure(self.canvas.figure)
ab.draggable()
self.subplot.axes.add_artist(ab)
os.remove(tfile.name)

Categories

Resources