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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
|
"""
Visualize Test Plots
This script will go through all the plots in the ``mpld3/test_plots``
directory, and save them as D3js to a single HTML file for inspection.
"""
import os
import glob
import sys
import gc
import traceback
import itertools
import json
import contextlib
import matplotlib
matplotlib.use('Agg') # don't display plots
import matplotlib.pyplot as plt
import mpld3
from mpld3 import urls
from mpld3.mpld3renderer import MPLD3Renderer
from mpld3.mplexporter import Exporter
plt.rcParams['figure.figsize'] = (6, 4.5)
plt.rcParams['savefig.dpi'] = 80
TEMPLATE = """
<html>
<head>
<script type="text/javascript" src={d3_url}></script>
<script type="text/javascript" src={mpld3_url}></script>
<style type="text/css">
.left_col {{
float: left;
width: 50%;
}}
.right_col {{
margin-left: 50%;
width: 50%;
}}
.fig {{
height: 500px;
}}
{extra_css}
</style>
</head>
<body>
<div id="wrap">
<div class="left_col">
{left_col}
</div>
<div class="right_col">
{right_col}
</div>
</div>
<script>
{js_commands}
</script>
</body>
</html>
"""
MPLD3_TEMPLATE = """
<div class="fig" id="fig{figid:03d}"></div>
"""
JS_TEMPLATE = """
!function(mpld3){{
{extra_js}
mpld3.draw_figure("fig{figid:03d}", {figure_json});
}}(mpld3);
"""
@contextlib.contextmanager
def mpld3_noshow():
"""context manager to use mpld3 with show() disabled"""
import mpld3
_show = mpld3.show
mpld3.show = lambda *args, **kwargs: None
yield mpld3
mpld3.show = _show
@contextlib.contextmanager
def use_dir(dirname=None):
"""context manager to temporarily change the working directory"""
cwd = os.getcwd()
if dirname is None:
dirname = cwd
os.chdir(dirname)
yield
os.chdir(cwd)
class ExecFile(object):
"""
Class to execute plotting files, and extract the mpl and mpld3 figures.
"""
def __init__(self, filename, execute=True, pngdir='_pngs'):
self.filename = filename
if execute:
self.execute_file()
if not os.path.exists(pngdir):
os.makedirs(pngdir)
basename = os.path.splitext(os.path.basename(filename))[0]
self.pngfmt = os.path.join(pngdir, basename + "_{0:2d}.png")
def execute_file(self):
"""
Execute the file, catching matplotlib figures
"""
dirname, fname = os.path.split(self.filename)
print('plotting {0}'.format(fname))
# close any currently open figures
plt.close('all')
# close any currently open figures
plt.close('all')
with mpld3_noshow() as mpld3:
with use_dir(dirname):
try:
# execute file, forcing __name__ == '__main__'
exec(open(os.path.basename(self.filename)).read(),
{'plt': plt, 'mpld3': mpld3, '__name__': '__main__'})
gcf = matplotlib._pylab_helpers.Gcf
fig_mgr_list = gcf.get_all_fig_managers()
self.figlist = sorted([manager.canvas.figure
for manager in fig_mgr_list],
key=lambda fig: fig.number)
except:
print(80 * '_')
print('{0} is not compiling:'.format(fname))
traceback.print_exc()
print(80 * '_')
finally:
ncol = gc.collect()
def iter_png(self):
for fig in self.figlist:
fig_png = self.pngfmt.format(fig.number)
fig.savefig(fig_png)
yield fig_png
def iter_json(self):
for fig in self.figlist:
renderer = MPLD3Renderer()
Exporter(renderer, close_mpl=False).run(fig)
fig, fig_json, extra_css, extra_js = renderer.finished_figures[0]
yield (json.dumps(fig_json), extra_js, extra_css)
def combine_testplots(wildcard='mpld3/test_plots/*.py',
outfile='_test_plots.html',
pngdir='_pngs',
d3_url=None, mpld3_url=None):
"""Generate figures from the plots and save to an HTML file
Parameters
----------
wildcard : string or list
a regexp or list of regexps matching files to test
outfile : string
the path at which the output HTML will be saved
d3_url : string
the URL of the d3 library to use. If not specified, a standard web
address will be used.
mpld3_url : string
the URL of the mpld3 library to use. If not specified, a standard web
address will be used.
"""
if isinstance(wildcard, str):
filenames = glob.glob(wildcard)
else:
filenames = itertools.chain(*(glob.glob(w) for w in wildcard))
fig_png = []
fig_json = []
for filename in filenames:
result = ExecFile(filename, pngdir=pngdir)
fig_png.extend(result.iter_png())
fig_json.extend(result.iter_json())
left_col = [MPLD3_TEMPLATE.format(figid=i)
for i in range(len(fig_json))]
js_commands = [JS_TEMPLATE.format(figid=figid,
figure_json=figjson,
extra_js=figjs)
for figid, (figjson, figjs, _) in enumerate(fig_json)]
right_col = ['<div class="fig"><img src="{0}"></div>\n'.format(fig)
for fig in fig_png]
extra_css = [tup[2] for tup in fig_json]
print("writing results to {0}".format(outfile))
with open(outfile, 'w') as f:
f.write(TEMPLATE.format(left_col="".join(left_col),
right_col="".join(right_col),
d3_url=json.dumps(d3_url),
mpld3_url=json.dumps(mpld3_url),
js_commands="".join(js_commands),
extra_css="".join(extra_css)))
def run_main():
import argparse
parser = argparse.ArgumentParser(description=("Run files and convert "
"output to D3"))
parser.add_argument("files", nargs='*', type=str)
parser.add_argument("-d", "--d3-url",
help="location of d3 library",
type=str, default=None)
parser.add_argument("-m", "--mpld3-url",
help="location of the mpld3 library",
type=str, default=None)
parser.add_argument("-o", "--output",
help="output filename",
type=str, default='_test_plots.html')
parser.add_argument("-j", "--minjs", action="store_true")
parser.add_argument("-l", "--local", action="store_true")
parser.add_argument("-n", "--nolaunch", action="store_true")
args = parser.parse_args()
if len(args.files) == 0:
wildcard = ['mpld3/test_plots/*.py', 'examples/*.py']
else:
wildcard = args.files
if args.d3_url is None:
args.d3_url = urls.D3_URL
if args.mpld3_url is None:
args.mpld3_url = urls.MPLD3_URL
if args.local:
args.d3_url = urls.D3_LOCAL
if args.minjs:
args.mpld3_url = urls.MPLD3MIN_LOCAL
else:
args.mpld3_url = urls.MPLD3_LOCAL
else:
if args.minjs:
args.mpld3_url = urls.MPLD3MIN_URL
print("d3 url: {0}".format(args.d3_url))
print("mpld3 url: {0}".format(args.mpld3_url))
combine_testplots(wildcard=wildcard,
outfile=args.output,
d3_url=args.d3_url,
mpld3_url=args.mpld3_url)
return args.output, args.nolaunch
if __name__ == '__main__':
outfile, nolaunch = run_main()
if not nolaunch:
# Open local file (works on OSX; maybe not on other systems)
import webbrowser
webbrowser.open_new('file://localhost' + os.path.abspath(outfile))
|