Include output from %matplotlib notebook backend as SVG in ipynb

前端 未结 2 1003
鱼传尺愫
鱼传尺愫 2021-02-19 21:47

This answer from a few years ago shows how you can make jupyter notebook create graphs as svg. The solution is to tell the InlineBackend to use svg as output.

相关标签:
2条回答
  • 2021-02-19 22:44

    From whatI understand from reading about matplotlib backends, nbagg, which is called using %matplotlib notebook uses the Agg (Anti-Grain Geometry) render which is not capable of rendering vector graphics. Unfortunately this is the only out of the box way of using an interactive inline backend for Jupyter.

    Docs Link https://matplotlib.org/faq/usage_faq.html#what-is-interactive-mode
    Similar Answer How to make matplotlibs nbagg backend generate SVGs?

    If you don't need the interactivity just keep use

    import pandas as pd
    from IPython.display import SVG, display
    from numpy import ndarray
    
    def svg_add(chart, size=(4,4), dpi=100):
        """Takes a chart, optional tuple of ints for size, int for dpi
        default is 4 by 4 inches with 100 dpi"""
    
        if type(chart) == ndarray:
            fig = chart[0].get_figure()
            fig.set_size_inches(size)
            fig.savefig("mybar.svg", dpi=dpi)
            display(SVG(filename='mybar.svg'))
        else:
            fig = chart.get_figure()
            fig.set_size_inches(size)
            fig.savefig("mybar.svg", dpi=dpi)
            display(SVG(filename='mybar.svg'))
    

    then

    df = pd.DataFrame([[2,5]],columns=['a','b'])
    bar_chart = df.plot(subplots=False, kind='bar')
    svg_add(chart=bar_chart,size=(3,3),dpi=100)
    #or
    #svg_add(bar_chart,(3,3),100)
    
    0 讨论(0)
  • 2021-02-19 22:46

    Since apparently even after a bounty period noone was able to provide a solution, a workaround may be the following.

    1. Create you notebook with %matplotlib notebook. Once you're satisfied with the result, save it.
    2. Use a copy of it and replace %matplotlib notebook with

      %matplotlib inline
      %config InlineBackend.figure_format = 'svg'
      

      Rerun the complete notebook. Save the result.

    3. Open the resulting ipynb file in a text editor and replace the previous two lines again with %matplotlib notebook.

    The final result will be a ipynb with svg images. But once opened and run, it will use the notebook backend for figure creation.

    0 讨论(0)
提交回复
热议问题