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

Skip to content

Commit fac467e

Browse files
committed
Easy specification of default output format for cairo backend
svn path=/trunk/matplotlib/; revision=3467
1 parent 3491dcf commit fac467e

5 files changed

Lines changed: 45 additions & 22 deletions

File tree

examples/backend_driver.py

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,18 @@
11
#!/usr/bin/env python
22
"""
33
This is used to drive many of the examples across the backends, for
4-
regression testing, and comparing backend efficiency
4+
regression testing, and comparing backend efficiency.
5+
6+
The script takes one or more arguments specifying backends
7+
to be tested, e.g.
8+
9+
python backend_driver.py agg ps cairo.png cairo.ps
10+
11+
would test the agg and ps backends, and the cairo backend with
12+
output to png and ps files.
13+
14+
If no arguments are given, a default list of backends will be
15+
tested.
516
"""
617

718
from __future__ import division
@@ -98,7 +109,11 @@ def drive(backend, python='python', switches = []):
98109

99110
exclude = failbackend.get(backend, [])
100111
switchstring = ' '.join(switches)
101-
112+
# Strip off the format specifier, if any.
113+
if backend.startswith('cairo'):
114+
_backend = 'cairo'
115+
else:
116+
_backend = backend
102117
for fname in files:
103118
if fname in exclude:
104119
print '\tSkipping %s, known to fail on backend: %s'%backend
@@ -107,17 +122,13 @@ def drive(backend, python='python', switches = []):
107122
print '\tdriving %s %s' % (fname, switchstring)
108123
basename, ext = os.path.splitext(fname)
109124
outfile = basename + '_%s'%backend
110-
# The following is temporary, until I put in a command-line
111-
# argument to specify the output.
112-
if backend.lower() == 'cairo':
113-
outfile += '.png'
114125
tmpfile_name = '_tmp_%s.py' % basename
115126
tmpfile = file(tmpfile_name, 'w')
116127

117128
tmpfile.writelines((
118129
'from __future__ import division\n',
119130
'import matplotlib\n',
120-
'matplotlib.use("%s")\n' % backend,
131+
'matplotlib.use("%s")\n' % _backend,
121132
'from pylab import savefig\n',
122133
))
123134
for line in file(fname):
@@ -138,18 +149,19 @@ def drive(backend, python='python', switches = []):
138149
#os.system('%s %s %s' % (python, tmpfile_name, switchstring))
139150
os.remove(tmpfile_name)
140151

141-
142152
if __name__ == '__main__':
143153
times = {}
144154
default_backends = ['Agg', 'PS', 'SVG', 'Template']
145155
if sys.platform == 'win32':
146156
python = r'c:\Python24\python.exe'
147157
else:
148158
python = 'python'
159+
all_backends = [b.lower() for b in mplbe.all_backends]
160+
all_backends.extend(['cairo.png', 'cairo.ps', 'cairo.pdf', 'cairo.svg'])
149161
backends = []
150162
switches = []
151163
if sys.argv[1:]:
152-
backends = [b for b in sys.argv[1:] if b in mplbe.all_backends]
164+
backends = [b.lower() for b in sys.argv[1:] if b.lower() in all_backends]
153165
switches = [s for s in sys.argv[1:] if s.startswith('--')]
154166
if not backends:
155167
backends = default_backends

lib/matplotlib/__init__.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,7 @@
176176
import sys, os, tempfile
177177

178178
from rcsetup import defaultParams, validate_backend, validate_toolbar
179+
from rcsetup import validate_cairo_format
179180

180181
major, minor1, minor2, s, tmp = sys.version_info
181182
_python23 = major>=2 and minor1>=3
@@ -782,9 +783,12 @@ def rcdefaults():
782783

783784
for s in sys.argv[1:]:
784785
if s.startswith('-d') and len(s) > 2: # look for a -d flag
786+
be_parts = s[2:].split('.')
785787
try:
786-
name = validate_backend(s[2:].strip())
788+
name = validate_backend(be_parts[0])
787789
rcParams['backend'] = name
790+
if name == 'Cairo' and len(be_parts) > 1:
791+
rcParams['cairo.format'] = validate_cairo_format(be_parts[1])
788792
except (KeyError, ValueError):
789793
pass
790794
# we don't want to assume all -d flags are backends, eg -debug

lib/matplotlib/backends/backend_cairo.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def _fn_name(): return sys._getframe(1).f_code.co_name
4040
from matplotlib.mathtext import math_parse_s_ft2font
4141
import matplotlib.numerix as numx
4242
from matplotlib.transforms import Bbox
43-
43+
from matplotlib import rcParams
4444

4545
_debug = False
4646
#_debug = True
@@ -523,6 +523,9 @@ def print_figure(self, fo, dpi=150, facecolor='w', edgecolor='w',
523523
if format is None and isinstance (fo, basestring):
524524
# get format from filename extension
525525
format = os.path.splitext(fo)[1][1:]
526+
if format == '':
527+
format = rcParams['cairo.format']
528+
fo = '%s.%s' % (fo, format)
526529

527530
if format is not None:
528531
format = format.lower()
@@ -532,9 +535,10 @@ def print_figure(self, fo, dpi=150, facecolor='w', edgecolor='w',
532535
elif format in ('pdf', 'ps', 'svg'):
533536
self._save (fo, format, orientation, **kwargs)
534537
elif format == 'eps': # backend_ps for eps
538+
warnings.warn('eps format is printed by ps backend, not cairo')
535539
from backend_ps import FigureCanvasPS as FigureCanvas
536540
fc = FigureCanvas(self.figure)
537-
fc.print_figure (filename, dpi, facecolor, edgecolor,
541+
fc.print_figure (fo, dpi, facecolor, edgecolor,
538542
orientation, **kwargs)
539543
else:
540544
warnings.warn('Format "%s" is not supported.\n'

lib/matplotlib/rcsetup.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,10 @@ def validate_fontsize(s):
184184
'silent', 'helpful', 'debug', 'debug-annoying',
185185
])
186186

187+
validate_cairo_format = ValidateInStrings('cairo_format',
188+
['png', 'ps', 'pdf', 'svg'],
189+
ignorecase=True)
190+
187191
validate_ps_papersize = ValidateInStrings('ps_papersize',[
188192
'auto', 'letter', 'legal', 'ledger',
189193
'a0', 'a1', 'a2','a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'a10',
@@ -211,16 +215,12 @@ def validate_ps_distiller(s):
211215

212216
def validate_negative_linestyle_legacy(s):
213217
try:
214-
res = validate_negative_linestyle(s)
215-
return res
216-
except:
217-
try:
218-
dashes = validate_nseq_float(2)(s)
219-
warnings.warn("Deprecated negative_linestyle specification; use 'solid' or 'dashed'")
220-
return (0, dashes) # (offset, (solid, blank))
221-
except:
222-
pass
223-
raise
218+
res = validate_negative_linestyle(s)
219+
return res
220+
except ValueError:
221+
dashes = validate_nseq_float(2)(s)
222+
warnings.warn("Deprecated negative_linestyle specification; use 'solid' or 'dashed'")
223+
return (0, dashes) # (offset, (solid, blank))
224224

225225
class ValidateInterval:
226226
"""
@@ -402,6 +402,7 @@ def __call__(self, s):
402402
'savefig.edgecolor' : ['w', validate_color], # edgecolor; white
403403
'savefig.orientation' : ['portrait', validate_orientation], # edgecolor; white
404404

405+
'cairo.format' : ['png', validate_cairo_format],
405406
'tk.window_focus' : [False, validate_bool], # Maintain shell focus for TkAgg
406407
'tk.pythoninspect' : [False, validate_bool], # Set PYTHONINSPECT
407408
'ps.papersize' : ['letter', validate_ps_papersize], # Set the papersize/type

matplotlibrc.template

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,8 @@ numerix : %(numerix)s # numpy, Numeric or numarray
244244
#savefig.facecolor : white # figure facecolor when saving
245245
#savefig.edgecolor : white # figure edgecolor when saving
246246

247+
#cairo.format : png # png, ps, pdf, svg
248+
247249
# tk backend params
248250
#tk.window_focus : False # Maintain shell focus for TkAgg
249251
#tk.pythoninspect : False # tk sets PYTHONINSEPCT

0 commit comments

Comments
 (0)