Is there an efficient way to store 2D plots as a vector graphic in python?

一个人想着一个人 提交于 2019-12-03 21:15:08

Here is an answer I suggested in the comments:

The large pdf/svg files result from storing every rectangle in pcolormesh as a vector graphic.

What I wanted to achieve with storing the plot as svg/pdf was to get a high-res image where the text is rendered once I insert the file in my latex document. The plot itself does not really need to be a vector graphic if the resolution is good enough.

So here is my suggestion (imported libraries are the same as above):

mpl.use('svg')
new_rc_params = {
    "font.family": 'Times', #probably python doesn't know Times, but it will replace it with a different font anyway. The final decision is up to the latex document anyway
    "font.size": 12, #choosing the font size helps latex to place all the labels, ticks etc. in the right place
    "font.serif": [],
    "svg.fonttype": 'none'} #to store text as text, not as path
mpl.rcParams.update(new_rc_params)

plt.figure(figsize = (6.49/2, 6.49/2)) #that's about half the text width of an A4 document
plt.pcolormesh(x, y, z, rasterized = True) # That's the trick. It will render the image already in python!
plt.xlabel('Math expression: \$a + b = c\$') # We need the backslashes because otherwise python will render the mathematic expression which will confuse latex
plt.savefig('test.svg', dpi = 1000, format = 'svg', bbox_inches = 'tight') # depends on your final figure size, 1000 dpi should be definitely enough for A4 documents

Once you have stored the svg file, open it in Inkscape. Save as pdf and set the tick at 'Omit text in PDF and create LaTex file'. In your latex file you have to use

\begin{figure}
    \centering
    \input{test.pdf_tex}
    \caption{This should have the same font type and size as your xlabel}
\end{figure}

to import your 2D plot. That's it :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!