Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 698b8d6

Browse files
committed
Moved backend_latex functionality into backend_ps - DSD
svn path=/trunk/matplotlib/; revision=1371
1 parent 44ecb26 commit 698b8d6

File tree

5 files changed

+120
-24
lines changed

5 files changed

+120
-24
lines changed

CHANGELOG

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
New entries should be added at the top
22

3+
2005-05-26 Moved backend_latex functionality into backend_ps. If
4+
text.usetex=True, the PostScript backend will use LaTeX to
5+
generate the .ps or .eps file. Ghostscript is required for
6+
eps output. - DSD
7+
38
2005-05-24 Fixed alignment and color issues in latex backend. - DSD
49

510
2005-05-21 Fixed raster problem for small rasters with dvipng -- looks

examples/tex_demo.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,14 @@
33
figure(1)
44
ax = axes([0.1, 0.1, 0.8, 0.7])
55
t = arange(0.0, 1.0+0.01, 0.01)
6-
s = cos(2*2*pi*t)
6+
s = cos(2*2*pi*t)+2
77
plot(t, s)
88

99
xlabel(r'\bf{time (s)}')
1010
ylabel(r'\it{voltage (mV)}',fontsize=16)
11-
title(r"\TeX\ is Number $\displaystyle\sum_{n=1}^\infty{-e^{i\pi} \over 2^n}$!",
11+
title(r"\TeX\ is Number $\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!",
1212
{'bbox':{'fc':0.8,'pad':0}}, fontsize=16, color='r')
1313
grid(True)
14-
savefig('tex_demo')
14+
savefig('tex_demo.eps')
1515

1616
show()

lib/matplotlib/backends/backend_ps.py

Lines changed: 109 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
def _fn_name(): return sys._getframe(1).f_code.co_name
99

1010
from cStringIO import StringIO
11-
from matplotlib import verbose, __version__, rcParams
11+
from matplotlib import verbose, __version__, rcParams, get_data_path
1212
from matplotlib._pylab_helpers import Gcf
1313
import matplotlib.agg as agg
1414
from matplotlib.afm import AFM
@@ -22,11 +22,10 @@ def _fn_name(): return sys._getframe(1).f_code.co_name
2222
from matplotlib.ft2font import FT2Font, KERNING_UNFITTED, KERNING_DEFAULT, KERNING_UNSCALED
2323
from matplotlib.mathtext import math_parse_s_ps, bakoma_fonts
2424
from matplotlib.text import Text
25+
from matplotlib.texmanager import TexManager
2526

2627
from matplotlib.transforms import get_vec6_scales
2728

28-
from matplotlib import get_data_path
29-
3029
from matplotlib.numerix import fromstring, UInt8, Float32, equal, alltrue, \
3130
nonzero, take, where, ones, put
3231
import binascii
@@ -123,6 +122,10 @@ def __init__(self, width, height, pswriter):
123122
self.width = width
124123
self.height = height
125124
self._pswriter = pswriter
125+
if rcParams['text.usetex']:
126+
self.textcnt = 0
127+
self.psfrag = []
128+
self.texmanager = TexManager()
126129

127130
# current renderer state (None=uninitialised)
128131
self.color = None
@@ -189,6 +192,13 @@ def get_text_width_height(self, s, prop, ismath):
189192
with FontPropertry prop
190193
191194
"""
195+
if rcParams['text.usetex']:
196+
fontsize = prop.get_size_in_points()
197+
l,b,r,t = self.texmanager.get_ps_bbox(s)
198+
w = (r-l)*fontsize/10.
199+
h = (t-b)*fontsize/10.
200+
#print s, w, h
201+
return w, h
192202

193203
if rcParams['ps.useafm']:
194204
if ismath: s = s[1:-1]
@@ -211,7 +221,7 @@ def get_text_width_height(self, s, prop, ismath):
211221
w, h = font.get_width_height()
212222
w /= 64.0 # convert from subpixels
213223
h /= 64.0
214-
print s, w, h
224+
#print s, w, h
215225
return w, h
216226

217227
def flipy(self):
@@ -552,6 +562,29 @@ def draw_rectangle(self, gc, rgbFace, x, y, width, height):
552562
ps = '%s box' % _nums_to_str(width, height, x, y)
553563
self._draw_ps(ps, gc, rgbFace, "rectangle")
554564

565+
def draw_tex(self, gc, x, y, s, prop, angle, ismath='TeX!'):
566+
"""
567+
draw a Text instance
568+
"""
569+
w, h = self.get_text_width_height(s, prop, ismath)
570+
fontsize = prop.get_size_in_points()
571+
corr = 0#w/2*(fontsize-10)/10
572+
pos = _nums_to_str(x-corr, y)
573+
thetext = 'psmarker%d' % self.textcnt
574+
scale = float(fontsize/10.0)
575+
color = '%1.3f,%1.3f,%1.3f'% gc.get_rgb()
576+
tex = r'\color[rgb]{%s} %s' % (color, s)
577+
self.psfrag.append(r'\psfrag{%s}[bl][bl][%f][%f]{%s}'%(thetext, scale, angle, tex))
578+
ps = """\
579+
gsave
580+
%(pos)s moveto
581+
(%(thetext)s)
582+
show
583+
grestore
584+
""" % locals()
585+
586+
self._pswriter.write(ps)
587+
self.textcnt += 1
555588

556589
def draw_text(self, gc, x, y, s, prop, angle, ismath):
557590
"""
@@ -876,9 +909,21 @@ def print_figure(self, outfile, dpi=72,
876909
title = None
877910
else:
878911
basename, ext = os.path.splitext(outfile)
879-
if not ext: outfile += '.ps'
880-
isEPSF = ext.lower().startswith('.ep')
881-
fh = file(outfile, 'w')
912+
if not ext:
913+
if rcParams['text.usetex']:
914+
ext = '.eps'
915+
outfile += ext
916+
else:
917+
ext = '.ps'
918+
outfile += ext
919+
if rcParams['text.usetex']:
920+
epsfile = basename + '.eps'
921+
psfile = basename + '.ps'
922+
texfile = basename + '.tex'
923+
latexh = file(texfile, 'w')
924+
fh = file(epsfile, 'w')
925+
else: fh = file(outfile, 'w')
926+
isEPSF = ext.lower().startswith('.ep') or rcParams['text.usetex']
882927
needsClose = True
883928
title = outfile
884929

@@ -942,26 +987,29 @@ def print_figure(self, outfile, dpi=72,
942987
if not isEPSF: print >>fh, "%%Pages: 1"
943988
print >>fh, "%%EndComments"
944989

945-
type42 = _type42 + [os.path.join(self.basepath, name) + '.ttf' \
946-
for name in bakoma_fonts]
947-
print >>fh, "%%BeginProlog"
948990
Ndict = len(psDefs)
949-
if not rcParams['ps.useafm']:
950-
Ndict += len(type42)
991+
print >>fh, "%%BeginProlog"
992+
if not rcParams['text.usetex']:
993+
type42 = _type42 + [os.path.join(self.basepath, name) + '.ttf' \
994+
for name in bakoma_fonts]
995+
if not rcParams['ps.useafm']:
996+
Ndict += len(type42)
997+
951998
print >>fh, "/mpldict %d dict def"%Ndict
952999
print >>fh, "mpldict begin"
9531000

9541001
for d in psDefs:
9551002
d=d.strip()
9561003
for l in d.split('\n'):
9571004
print >>fh, l.strip()
958-
if not rcParams['ps.useafm']:
959-
for font in type42:
960-
print >>fh, "%%BeginFont: "+FT2Font(str(font)).postscript_name
961-
print >>fh, encodeTTFasPS(font)
962-
print >>fh, "%%EndFont"
963-
964-
print >>fh, "%%EndProlog"
1005+
if not rcParams['text.usetex']:
1006+
if not rcParams['ps.useafm']:
1007+
for font in type42:
1008+
print >>fh, "%%BeginFont: "+FT2Font(str(font)).postscript_name
1009+
print >>fh, encodeTTFasPS(font)
1010+
print >>fh, "%%EndFont"
1011+
1012+
print >>fh, "%%EndProlog"
9651013

9661014
if not isEPSF: print >>fh, "%%Page: 1 1"
9671015
print >>fh, "mpldict begin"
@@ -981,6 +1029,48 @@ def print_figure(self, outfile, dpi=72,
9811029

9821030
if not isEPSF: print >>fh, "%%EOF"
9831031
if needsClose: fh.close()
1032+
1033+
if rcParams['text.usetex']:
1034+
if defaultPaperType in ['a4','a5','b5','letter','legal','executive']:
1035+
latexPaperType = defaultPaperType + 'paper'
1036+
else:
1037+
verbose.report('"%s" is not a valid LaTeX papertype.'% defaultPaperType + \
1038+
'Defaulting to letter.')
1039+
latexPaperType = 'letterpaper'
1040+
print >>latexh, r"""\documentclass[%s]{article}
1041+
\usepackage{psfrag}
1042+
\usepackage{type1cm}
1043+
\usepackage[dvips]{graphicx}
1044+
\usepackage{color}
1045+
\pagestyle{empty}
1046+
\begin{document}
1047+
\begin{figure}[th!]
1048+
\begin{center}
1049+
%s
1050+
\includegraphics{%s}
1051+
\end{center}
1052+
\end{figure}
1053+
\end{document}
1054+
"""% (latexPaperType, '\n'.join(renderer.psfrag), epsfile)
1055+
1056+
latexh.close()
1057+
1058+
command = 'latex %s' % texfile
1059+
os.system(command)
1060+
command = 'dvips -o %s %s' % (psfile, basename+'.dvi')
1061+
os.system(command)
1062+
if ext.startswith('.ep'):
1063+
command = 'ps2epsi %s %s' % (psfile, outfile)
1064+
msg = os.system(command)
1065+
if msg==32512: raise 'ps2epsi: command not found! Please install Ghostscript.'
1066+
os.remove(psfile)
1067+
os.remove(texfile)
1068+
os.remove(basename+'.dvi')
1069+
try: os.remove(basename+'.log')
1070+
except OSError: pass
1071+
try: os.remove(basename+'.aux')
1072+
except OSError: pass
1073+
9841074

9851075
class FigureManagerPS(FigureManagerBase):
9861076
pass

lib/matplotlib/texmanager.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,8 @@ def make_dvi(self, tex, force=0):
4444

4545
logfile = prefix + '.log'
4646
fh = file(fname, 'w')
47-
s = r"""\nopagenumbers
47+
s = r"""\def\frac#1#2{ {#1 \over #2} }
48+
\nopagenumbers
4849
\hsize=72in
4950
\vsize=72in
5051
%s

lib/matplotlib/text.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,7 @@ def draw(self, renderer):
283283
if angle==0:
284284
if ismath!='TeX': m = None
285285
else: m = self._rgxsuper.match(self._text)
286-
if m is not None:
286+
if m is not None and not rcParams['text.usetex']:
287287
bbox, info = self._get_layout_super(self._renderer, m)
288288
base, xt, yt = info[0]
289289
renderer.draw_text(gc, xt, yt, base,

0 commit comments

Comments
 (0)