Skip to content

Commit f920bfc

Browse files
committed
SVG graphics in matplotlib shell!
(via cairosvg to convert to PNG)
1 parent 7581905 commit f920bfc

File tree

3 files changed

+47
-10
lines changed

3 files changed

+47
-10
lines changed

mathicsscript/format.py

Lines changed: 44 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,41 @@
22
Format Mathics objects
33
"""
44

5-
import random
65
import math
76
import networkx as nx
7+
import random
8+
from tempfile import NamedTemporaryFile
9+
10+
try:
11+
import matplotlib.pyplot as plt
12+
except ImportError:
13+
plt = None
14+
15+
try:
16+
import matplotlib.image as mpimg
17+
except ImportError:
18+
mpimg = None
19+
20+
try:
21+
from cairosvg import svg2png
22+
except ImportError:
23+
svg2png = None
824

925

1026
def format_output(obj, expr, format=None):
27+
def eval_boxes(result, fn, obj, **options):
28+
try:
29+
boxes = fn(evaluation=obj, **options)
30+
except BoxError:
31+
boxes = None
32+
if not hasattr(obj, "seen_box_error"):
33+
obj.seen_box_error = True
34+
obj.message(
35+
"General", "notboxes", Expression("FullForm", result).evaluate(obj)
36+
)
37+
38+
return boxes
39+
1140
if format is None:
1241
format = obj.format
1342

@@ -28,12 +57,20 @@ def format_output(obj, expr, format=None):
2857
if len(leaves) == 1:
2958
expr = leaves[0]
3059
elif expr_type in ("System`Graphics", "System`Plot"):
31-
result = "-System Graphics-"
32-
result = Expression("StandardForm", expr)
33-
result = result.format(obj, "System`MathMLForm")
34-
# ml_str = result.leaves[0].leaves[0]
35-
# FIXME: not quite right. Need to parse out strings
36-
# display_svg(str(ml_str))
60+
form_expr = Expression("StandardForm", expr)
61+
result = form_expr.format(obj, "System`StandardForm")
62+
svg_str = eval_boxes(result, result.boxes_to_svg, obj)
63+
if plt:
64+
temp_png = NamedTemporaryFile(
65+
mode="w+b", suffix=".png", prefix="mathicsscript-"
66+
)
67+
svg2png(bytestring=svg_str, write_to=temp_png.name)
68+
plt.axes().set_axis_off()
69+
img = mpimg.imread(temp_png)
70+
plt.imshow(img)
71+
plt.show()
72+
temp_png.close()
73+
return expr_type
3774

3875
if format == "text":
3976
result = expr.format(obj, "System`OutputForm")
@@ -359,7 +396,6 @@ def format_graph(G):
359396
Format a Graph
360397
"""
361398
# FIXME handle graphviz as well
362-
import matplotlib.pyplot as plt
363399

364400
global node_size
365401
global cached_pair

requirements-extra.txt

Lines changed: 0 additions & 2 deletions
This file was deleted.

requirements-full.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
PyYAML # Used for admin-tools/make-tables.sh to build JSON tables
2+
PyQT5 # For interactive display of graphs via matplotlib
3+
cairosvg # For rendering Plots and Graphs as SVGs via matplotlib

0 commit comments

Comments
 (0)