Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib: generating vector plot

Tags:

I want to generate a vector plot with matplotlib. I tried hard - but the output is a raster image. Here's what I use:

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

and finally:

myfig.savefig('myfig.eps', format='eps')

I've found that export to ps gives a vector image, but the problem with eps remains.

like image 560
pvl Avatar asked Feb 13 '12 18:02

pvl


People also ask

How do I plot a vector in Python?

MatPlotLib with PythonCreate a matrix of 2×3 dimension. Create an origin point, from where vecors could be originated. Plot a 3D fields of arrows using quiver() method with origin, data, colors and scale=15.

Can we plot a graph of vector plot?

You can visualize a vector field by plotting vectors on a regular grid, by plotting a selection of streamlines, or by using a gradient color scheme to illustrate vector and streamline densities. You can also plot a vector field from a list of vectors as opposed to a mapping.

What is MatPlotLib quiver?

Quiver plot is basically a type of 2D plot which shows vector lines as arrows. This type of plots are useful in Electrical engineers to visualize electrical potential and show stress gradients in Mechanical engineering.


2 Answers

I use the following code:

from matplotlib import pyplot as plt

fig, ax = plt.subplots() # or 
fig.savefig('filename.eps', format='eps')
like image 92
hurrial Avatar answered Oct 11 '22 03:10

hurrial


If you need emf files as output format, e.g. to insert high quality plots into ms word/powerpoint and you are willing to use inkscape as converter you can apply this solution:

from matplotlib import pyplot as plt
import subprocess, os

def plot_as_emf(figure, **kwargs):
    inkscape_path = kwargs.get('inkscape', "C://Program Files//Inkscape//inkscape.exe")
    filepath = kwargs.get('filename', None)

    if filepath is not None:
        path, filename = os.path.split(filepath)
        filename, extension = os.path.splitext(filename)

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

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

        subprocess.call([inkscape_path, svg_filepath, '--export-emf', emf_filepath])
        os.remove(svg_filepath)

In order to test this function you can run a simple example:

plt.plot([1,2], [4,5])
fig = plt.gcf()
plot_as_emf(fig, filename="C:/test.emf")
like image 41
tuxiano Avatar answered Oct 11 '22 04:10

tuxiano