Search code examples
pythonmatplotlibsvginkscape

Export matplotlib as emf and avoid black bacground fill


The previous discussion [1] helps us to export a matplotlib plot as an .emf file. However, the strange error is that the output file has nodes filled with black background as shown below.

How is it possible to obtain the .emf exactly as the .svg?

import matplotlib.pyplot as plt
import subprocess, os

# Graph with 4 nodes - its coordinates
x = [0, 5, 5, 0]
y = [0, 0, 5, 5]

fig, ax = plt.subplots()

# Plot the vertices
for i in range(len(x)):
        ax.plot(x[i], y[i], 'ro',
                 markersize = 12,
                 fillstyle = 'none',
                 label = 'A')

# Plot the edges
plt.plot(x,y)

# Legend
handles, labels = plt.gca().get_legend_handles_labels()
by_label = dict(zip(labels, handles))
plt.legend(by_label.values(), by_label.keys())

# File export
inkscape_path = "C://Program Files//Inkscape//bin//inkscape.exe"
out_file = "C:/Users/banbar/Desktop/out1.emf"

path, filename = os.path.split(out_file)
filename, extension = os.path.splitext(filename)

svg_filepath = os.path.join(path, filename+'.svg')
emf_filepath = os.path.join(path, filename+'.emf')

fig.savefig(svg_filepath, format='svg')

subprocess.call([inkscape_path, svg_filepath, '--export-filename', emf_filepath])   

enter image description here


Solution

  • This is only one half of the answer, which is the SVG half:

    When you select one of those squares in Inkscape, you will probably notice that it says 'Fill unset' in the bottom left where the fill indicator is.

    That would be because matplotlib leaves the fill attribute out entirely. A valid value in SVG would be 'none' or a fill color with opacity = 0.

    I've found a link about how to determine the fill color here: https://matplotlib.org/2.1.1/api/_as_gen/matplotlib.pyplot.plot.html

    You should be able to figure out the rest from there, hopefully.