Altair: specify a renderer that's enabled by default

uppi :

Is there a way to enable a renderer except for calling alt.renderers.enable('mimebundle') in code? So if the user imports altair she doesn't have to perform any additional actions?

For example, in plotly you can set an environment variable PLOTLY_RENDERER=plotly_mimetype. Is there something similar in altair?

jakevdp :

No, Altair does not currently have any mechanism to specify a renderer aside from calling alt.renderers.enable.

But if you are using Jupyter, you could provide an IPython startup script that does this; for example, you can create a file at the path ~/.ipython/profile_default/startup/start.py with the following contents:

import altair
altair.renderers.enable('notebook')

and this will be executed at the start of any Jupyter/IPython session.

If you don't wish to import Altair in every session, you could instead define in this file a Python import hook that will execute custom code the first time Altair is imported. For example, it might look something like this:

import imp
import os
import sys

class _AltairImportHook(object):
  def find_module(self, fullname, path=None):
    if fullname != 'altair':
      return None
    self.module_info = imp.find_module(fullname, path)
    return self

  def load_module(self, fullname):
    """Loads Altair normally and runs pre-initialization code."""
    previously_loaded = fullname in sys.modules
    altair = imp.load_module(fullname, *self.module_info)

    if not previously_loaded:
      try:
        altair.renderers.enable('notebook')
      except:
        pass
    return altair

sys.meta_path = [_AltairImportHook()] + sys.meta_path

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=3907&siteId=1