Matplotlib output to PDF for Corel Draw - python

Update: The fonts issue was actaully solved by using rc("pdf", fonttype=42) but unfortunately it is combined with another - whenever is used any type of marker I tried CorelDraw comes with error "File is corrupted".
When I output my charts from Matplotlib into PDF I am not able to open it in Corel Draw. I highly suspect that the major issue might be with texts / fonts.
Simple code example which I need update to make PDF with text and markers import correctly in Corel Draw:
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
from matplotlib import rc
rc("pdf", fonttype=42)
with PdfPages("simple.pdf") as pdf:
points_y = points_x = [1,2,3]
plt.plot(points_x, points_y, marker="o")
pdf.savefig()
plt.close()
Example of Corel vs Matplotlib / PDF Reader when not used rc("pdf", fonttype=42) and marker. If marker used PDF doesn't open and CorelDraw says "File is corrupted".

It turned out there are two important issues which ruins import of Matplotlib generated PDF into CorelDraw.
Setting up the font type from the default rc("pdf", fonttype=3) to rc("pdf", fonttype=42)
Not using multiple markers. Only one marker per plot allowed! Possible to replace by text. (no pyplot.scatter, not in pyplot.plot etc.). When using any markers in number of 2 or more per plot CorelDraw finds the PDF corrupted and wont open it at all.
Code rewritten to plot only one marker per plot plus only one marker in the legend:
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
from matplotlib import rc
rc("pdf", fonttype=42)
with PdfPages("simple.pdf") as pdf:
points_y = points_x = [1,2,3]
plt.plot(points_x, points_y,color="r")
# plot points one be one otherwise "File is corrupted" in CorelDraw
# also plot first point out of loop to make appropriate legend
plt.plot(points_x[0], points_y[0],marker="o",color="r",markerfacecolor="b",label="Legend label")
for i in range(1,len(points_x)):
plt.plot(points_x[i], points_y[i],marker="o",markerfacecolor="b")
plt.legend(numpoints=1) #Only 1 point in legend because in CorelDraw "File is corrupted" if default two or more
pdf.savefig()
plt.close()
As a possible replacement for points (markers) pyplot.text can be used, for my example in question updated code looks like this:
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
from matplotlib import rc
rc("pdf", fonttype=42)
with PdfPages("simple.pdf") as pdf:
points_y = points_x = [1,2,3]
plt.plot(points_x, points_y)
# print points as + symbol
for i in range(len(points_x)):
plt.text(points_x[i], points_y[i],"+",ha="center", va="center")
pdf.savefig()
plt.close()

Related

Saving a plot from multiple subplots

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
fig,ax=plt.subplots(2,2,figsize=(15,10))
x=np.linspace(-3,3)
ax[0,0].plot(x,foo-function)
now I need a way to save each of the 4 plots into one file like this:
plt1=topleft_plot.saveNOTfigBUTplot('quadfunction.pdf')
how?
Using the answer here: https://stackoverflow.com/a/4328608/16299117
We can do the following to save a SINGLE subplot from the overall figure:
import matplotlib.pyplot as plt
import numpy as np
fig,ax=plt.subplots(2,2,figsize=(15,10))
x=np.linspace(-3,3)
ax[0,0].plot(x,x**2) # This is just to make an actual plot.
# I am not using jupyter notebook, so I use this to show it instead of %inline
plt.show()
# Getting only the axes specified by ax[0,0]
extent = ax[0,0].get_window_extent().transformed(fig.dpi_scale_trans.inverted())
# Saving it to a pdf file.
fig.savefig('ax2_figure.pdf', bbox_inches=extent.expanded(1.1, 1.2))
EDIT: I believe I may have misunderstood what you want. If you want to save EACH plot individually, say as 4 different pages in a pdf, you can do the following adapted from this answer: https://stackoverflow.com/a/29435953/16299117
This will save each subplot from the figure as a different page in a single pdf.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
fig,ax=plt.subplots(2,2,figsize=(15,10))
x=np.linspace(-3,3)
ax[0,0].plot(x,x**2) # This is just to make an actual plot.
with PdfPages('foo.pdf') as pdf:
for x in range(ax.shape[0]):
for y in range(ax.shape[1]):
extent = ax[x, y].get_window_extent().transformed(fig.dpi_scale_trans.inverted())
pdf.savefig(bbox_inches=extent.expanded(1.1, 1.2))

Reading matplotlib graphs from file

Is it possible to read (say) 4 .jpeg graphs produced by matplotlib into matplotlib again so that they can be replotted as subplots? If so, how would I do it?
If you really want to do it by reading jpeg files of existing plots (noting the comments), one way might be to read in the graphs in with scipy.misc.imread. I've set the axis labels off assuming you saved the original graphs with labels and everything.
import matplotlib.pyplot as plt
from scipy.misc import imread
# Create a figure with 2x2 arranged subplots
fig, ax = plt.subplots(2,2)
# Plot images one by one here
# (Just using the same jpeg file in this example...)
im1 = imread("graph1.jpg")
ax[0,0].imshow(im1)
ax[0,0].axis('off')
ax[0,1].imshow(im1)
ax[0,1].axis('off')
ax[1,0].imshow(im1)
ax[1,0].axis('off')
ax[1,1].imshow(im1)
ax[1,1].axis('off')
fig.show()

How to save Matplotlib.pyplot.loglog to file?

I am trying to generate the log-log plot of a vector, and save the generated plot to file.
This is what I have tried so far:
import matplotlib.pyplot as plt
...
plt.loglog(deg_distribution,'b-',marker='o')
plt.savefig('LogLog.png')
I am using Jupyter Notebook, in which I get the generated graph as output after statement 2 in the above code, but the saved file is blank.
Notice that pyplot has the concept of the current figure and the current axes. All plotting commands apply to the current axes. So, make sure you plot in the right axes. Here is a WME.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.loglog(range(100), 'b-',marker='o')
plt.savefig('test.png') # apply to the axes `ax`

(Matplotlib, python) long subplots, scrolling

I would like to create a pdf file [by using plt.savefig("~~~.pdf")]
containing lots of (about 20) subplots
each of which is drawing timeseries data.
I am using a matplotlib library with python language.
Each subplot may be long, and I want to put the subplots
horizontally.
Therefore, the figure should be very long (horizontally), so the horizontal scroll bar should be needed!
Is there any way to do this?
some example code will be appreciated!
The following is my sample code.
I just wanted to draw 10 sine graphs arranged horizontally
and save it as pdf file.
(but I'm not pretty good at this. so the code may looks to be weird to you.. :( )
from matplotlib import pyplot as plt
import numpy as np
x=np.linspace(0,100,1000)
y=np.sin(x)
numplots=10
nr=1
nc=numplots
size_x=nc*50
size_y=size_x*3/4
fig=plt.figure(1,figsize=(size_x,size_y))
for i in range(nc):
ctr=i+1
ax=fig.add_subplot(nr,nc,ctr)
ax.plot(x,y)
plt.savefig("longplot.pdf")
plt.clf()
Thank you!
You should do that using the backend "matplotlib.backends.backend_pdf". This enables you to save matplotlib graphs in pdf format.
I have simplified your code a bit, here is a working example:
from matplotlib import pyplot as plt
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
x = np.linspace(0,100,1000)
y = np.sin(x)
nr = 10
nc = 1
for i in range(nr):
plt.subplot(nr, nc, i + 1)
plt.plot(x, y)
pdf = PdfPages('longplot.pdf')
pdf.savefig()
pdf.close()
I hope this helps.
In the link below there is a solution, which can help you, since it was helpful to me either.
Scrollbar on Matplotlib showing page
But if you have many subplots, I am afraid your problem won't be solved. Since it will shrink each graph anyway. In that case it will be better to break your graphs into smaller and separate parts.

Blank image when saving an imshow matplotlib figure in iPython notebook

I'm using iPython notebook w/ matplotlib to display a bunch of images inline, but now it's come time to save a number of these images (think for-loop, i.e. not a small number of images to save). My issue seems to be something to do with how I'm using iPython since I could do this alright when my script was a standalone.
%matplotlib inline
import matplotlib.pyplot as plt
....
grid_z2 = griddata(....)
fig = plt.figure()
ax = fig.add_axes([1,1,1,1])
plt.imshow(grid_z2.transpose(),origin='Lower')
plt.colorbar()
plt.draw()
fig.savefig('slicemap.png')
I have also tried plt.savefig(), fig1 = plt.gcf() before plt.imshow then trying to save fig1... always every single time a blank file.
Any suggestions?

Categories

Resources