-
Notifications
You must be signed in to change notification settings - Fork 9
/
texfig.py
60 lines (50 loc) · 1.79 KB
/
texfig.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""
Utility to generate PGF vector files from Python's Matplotlib plots to use in LaTeX documents.
Read more at https://github.com/knly/texfig
"""
import matplotlib as mpl
mpl.use('pgf')
from math import sqrt
default_width = 5.78853 # in inches
default_ratio = (sqrt(5.0) - 1.0) / 2.0 # golden mean
mpl.rcParams["text.usetex"] = True
mpl.rcParams["pgf.texsystem"] = "xelatex"
mpl.rcParams["pgf.rcfonts"] = False
mpl.rcParams["font.family"] = "serif"
mpl.rcParams["font.sans-serif"] = []
mpl.rcParams["font.monospace"] = []
mpl.rcParams["figure.figsize"] = [default_width, default_width * default_ratio]
mpl.rcParams[ "pgf.preamble"] = "\n".join([
# put LaTeX preamble declarations here
r"\usepackage[utf8x]{inputenc}",
r"\usepackage[T1]{fontenc}",
# macros defined here will be available in plots, e.g.:
r"\newcommand{\vect}[1]{#1}",
# You can use dummy implementations, since your LaTeX document
# will render these properly, anyway.
])
import matplotlib.pyplot as plt
"""
Returns a figure with an appropriate size and tight layout.
"""
def figure(width=default_width, ratio=default_ratio, pad=0, *args, **kwargs):
fig = plt.figure(figsize=(width, width * ratio), *args, **kwargs)
fig.set_tight_layout({
'pad': pad
})
return fig
"""
Returns subplots with an appropriate figure size and tight layout.
"""
def subplots(width=default_width, ratio=default_ratio, *args, **kwargs):
fig, axes = plt.subplots(figsize=(width, width * ratio), *args, **kwargs)
fig.set_tight_layout({
'pad': 0
})
return fig, axes
"""
Save both a PDF and a PGF file with the given filename.
"""
def savefig(filename, *args, **kwargs):
plt.savefig(filename + '.pdf', *args, **kwargs)
plt.savefig(filename + '.pgf', *args, **kwargs)