Search code examples
matlabvector-graphicspostscript

How to save a Matlab histogram as vector graphic?


When saving a histogram like this:

x = randn(10000,1);
h = histogram(x)

saveas(gcf, 'test','epsc')

The resulting postscripts contains some form of raw bitmap. That looks really ugly, when embedded in a pdf.

How can I save a histogram as a vector graphic?


Solution

  • You could also just save the figure as a pdf which uses vector graphics.

    x = randn(10000,1);
    h = histogram(x);
    
    % set proper paper size before generating pdf
    set(gcf, 'Units', 'Inches');
    pos = get(gcf, 'Position');
    set(gcf, 'PaperPositionMode', 'Auto', 'PaperUnits', 'Inches', 'PaperSize', [pos(3), pos(4)]);
    print(gcf, 'test.pdf', '-dpdf', '-r0');
    

    Disclaimer I use this code a lot when I embed figures in LaTeX documents but I'm pretty sure I copied it from somewhere online (possible SO).