I have a Font problem in eps-files from matplotlib.
The font show correctly in die eps file, but when I paste the file in Microsoft Word, it doesnt Show the text (Labels, ticks, title...)
I already tryed to change the maplotlib.rcParams because that was the solution for other problems with text in eps files, but nothing worked.
EDIT: already changed matplotlib.use("xxx") too, did not help.
my code:
# -*- coding: utf-8 -*-
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
fig = plt.figure(figsize=(12,10))
ax = fig.add_subplot(111, projection='3d')
plt.title("lalala",family='Courier New')
x = range(len(a))
y = range(len(a))
X,Y = np.meshgrid(x,y)
Z = a
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
ax.plot_surface(X,Y,Z, cmap=plt.cm.Reds, cstride=1, rstride=1,alpha=0.3)
plt.savefig("texttestqua.eps")
plt.show()
is it possible to "draw" the text in the eps file? So that the text is not a "font" but just graphic-vectors?
I am not entirely sure if your problem stems from the inability of matplotlib to save your eps correctly or the inability of Microsoft Word to load vector graphics other than emf/wmf...
Nonetheless, I am giving it a try...
There are quite a lot of backends (GTK GTKAgg GTKCairo GTK3Agg GTK3Cairo CocoaAgg MacOSX Qt4Agg Qt5Agg TkAgg WX WXAgg Agg Cairo GDK PS PDF SVG), have you tried them all or at least a plausible subset?
Does it work for example with PS?
I am using the TkAgg backend here and your script produces the following output for me:
but when I paste the file in Microsoft Word, it doesnt Show the text (Labels, ticks, title...)
Afaik Microsoft Word does not support vector graphics natively unless it is emf. See this link for further guidance.
If that does not solve your problem, please consider formulating an explicit problem.
Related
I noticed the following issue when plotting axis labels and text in matplotlib with tex enabled, specifically when the font size is set to small integer values. See the code below.
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rc('text', usetex=True)
f,ax = plt.subplots(dpi=200)
ax.set_axis_off()
for i in range(3,8):
ax.text(0.15,0.05*i,r'fontsize=%d$\pm0.1:$'%i,fontsize=i)
ax.text(0.35,0.05*i,r'$E_E$',fontsize=i-0.01)
ax.text(0.4,0.05*i,r'$E_E$',fontsize=i)
ax.text(0.45,0.05*i,r'$E_E$',fontsize=i+0.01)
ax.set_ylim([0,0.5])
plt.show()
This produces:
Notice that when the font size is 5, the subscript is more or less the same size as the normal text. More subtle issues also persist for font sizes of 6 and 7. Adding ±0.01 fixes it, but it's still kinda weird and annoying. Does anybody know what's going on here or how it might be fixed?
In matplotlib, one can easily use latex script to label axes, or write legends or any other text. But is there a way to use new fonts such as 'script-r' in matplotlib? In the following code, I am labelling the axes using latex fonts.
import numpy as np
import matplotlib.pyplot as plt
tmax=10
h=0.01
number_of_realizations=6
for n in range(number_of_realizations):
xpos1=0
xvel1=0
xlist=[]
tlist=[]
t=0
while t<tmax:
xlist.append(xpos1)
tlist.append(t)
xvel1=np.random.normal(loc=0.0, scale=1.0, size=None)
xpos2=xpos1+(h**0.5)*xvel1 # update position at time t
xpos1=xpos2
t=t+h
plt.plot(tlist, xlist)
plt.xlabel(r'$ t$', fontsize=50)
plt.ylabel(r'$r$', fontsize=50)
plt.title('Brownian motion', fontsize=20)
plt.show()
It produces the following figure
But I want 'script-r' in place of normal 'r'.
In latex one has to add the following lines in preamble to render 'script-r'
\DeclareFontFamily{T1}{calligra}{}
\DeclareFontShape{T1}{calligra}{m}{n}{<->s*[2.2]callig15}{}
\DeclareRobustCommand{\sr}{%
\mspace{-2mu}%
\text{\usefont{T1}{calligra}{m}{n}r\/}%
\mspace{2mu}%
}
I don't understand how to do this in matplotlib. Any help is appreciated.
Matplotlib uses it's own hand-rolled (pure Python) implementation of TeX to do all of the math text stuff, so you absolutely cannot assume that what works in standard LaTeX will work with Matplotlib. That being said, here's how you do it:
Install the calligra font so that Matplotlib can see it, then rebuild the font cache.
Lots of other threads deal with how to do this, I'm not going to go into detail, but here's some reference:
Use a font installed in a random spot on your filesystem.
How to install a new font into the Matplotlib managed font cache.
List all fonts currently known to your install of Matplotlib.
Replace one of Matplotlib's TeX font families with your font of choice.
Here's a function I wrote a while ago that reliably does that:
import matplotlib
def setMathtextFont(fontName='Helvetica', texFontFamilies=None):
texFontFamilies = ['it','rm','tt','bf','cal','sf'] if texFontFamilies is None else texFontFamilies
matplotlib.rcParams.update({'mathtext.fontset': 'custom'})
for texFontFamily in texFontFamilies:
matplotlib.rcParams.update({('mathtext.%s' % texFontFamily): fontName})
For you, a good way to use the function would be to replace the font used by \mathcal with calligra:
setMathtextFont('calligra', ['cal'])
Label your plots, for example, r'$\mathcal{foo}$', and the contents of the \math<whatever> macro should show up in the desired font.
Here's how you'd change your label-making code:
plt.ylabel(r'$\mathcal{r}$', fontsize=50)
and that should do it.
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()
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.
I'm trying to use Matplotlib & Python in Xcode to generate scientific graphics. My boss would like them to be in LaTeX with matching fonts. I know you can modify the fonts in python with something like this:
from matplotlib import rc
rc('font',**{'family':'serif','serif':['Computer Modern Roman']})
rc('text', usetex=True)
Unfortunately, opening or saving the figure with plt.show() or plt.savefig() gives a string of errors, eventually leading to OSError: [Errno 2] No such file or directory.
I know "Google is your friend", but I haven't managed to find anything on how to go about solving this. Any help would be greatly appreciated.
I usually find it easiest to directly specify the font file I'm after. Here's an example:
import matplotlib.pyplot as plt
import matplotlib.font_manager
from numpy import *
# cmunso.otf is a randomly selected font in my tex installation
path = '/usr/local/texlive/2012/texmf-dist/fonts/opentype/public/cm-unicode/cmunso.otf'
f0 = matplotlib.font_manager.FontProperties()
f0.set_file(path)
plt.figure()
plt.xlim(0,1.)
plt.ylim(0,1.)
d = arange(0, 1, .1)
plt.plot(d, d, "ob", label='example')
plt.text(.5, .1, 'text.. abcdef', fontproperties=f0, size=30)
plt.xlabel("x label", fontproperties=f0)
plt.legend(prop=f0, loc=2)
I'm not a font expert, but I think the reason this is easier is that font selection often has a cascading set of defaults for when the way you specify the font doesn't exactly match the way the system does. The file, though, is easy to find and specify exactly (though it's obviously less portable).
Note that for xlabel and text the keyword is fontproperties and for legend it's prop.