2

I'm using a Databricks notebook. For various reasons, I need to render charts individually (concat doesn't give me the results I want) and I can't put the chart object at the end of the cell. I want to render each chart and do some processing. Here's some simple code that shows what I want to do.

import altair as alt
import pandas as pd

alt.renderers.enable('default')
df = pd.DataFrame({'x':  [1,2,3,4,5],
                   'y1': [1,2,3,4,5],
                   'y2': [6,7,8,9,10]})

for y in ['y1', 'y2']:
  chart = (alt.Chart(df, title="{0} vs x".format(y))
           .mark_line()
           .encode(x=alt.X('x:Q'),
                   y=alt.Y(y, title='Score')))
  chart.display()
  pass # More code that does stuff

Unfortunately, the output is:

alt.Chart(...)
alt.Chart(...)

I've tried vega version 2.2.0, 3.4.0, and 3.5.0 and I still get the same problem. I'm using altair version 4.1.0, IPython version 7.19.0, and Python 3.8.8.

I've tried different renderers ('mimetype', 'notebook') and I didn't get anything.

Does anyone know how to get the display() method working in Databricks?

Mike Woodward
  • 211
  • 2
  • 10

1 Answers1

1

You can use an object of HConcatChart to merge n number of charts you want to create -

import altair as alt
import pandas as pd

alt.renderers.enable('default')
df = pd.DataFrame({'x':  [1,2,3,4,5],
                   'y1': [1,2,3,4,5],
                   'y2': [6,7,8,9,10]})

base_chart_x = alt.HConcatChart()
base_chart_y = alt.HConcatChart()

for y in ['y1', 'y2']:
    chart = (alt.Chart(df, title="{0} vs x".format(y))
       .mark_line()
       .encode(x=alt.X('x:Q'),
               y=alt.Y(y, title='Score')))

    #### | --> Adds Charts Horizontally 
    base_chart_x |= chart

    #### & --> Adds Charts Vertically 
    base_chart_y &= chart

Horizontal Concat (base_chart_x)

Vertical Concat (base_chart_y)

Furthermore you can control the merging using the for loop with enumerate , flipping the merge after every 2-3 charts to generate a grid

Vaebhav
  • 4,672
  • 1
  • 13
  • 33
  • Thanks @Vaebhav, but I need to save some charts as SVG (I don't know ahead of time which ones). When I merge multiple charts into one, I lose the ability to export some of them individually as SVGs. I can't use Concat for this reason. – Mike Woodward Jun 23 '21 at 20:17
  • Probably if thats the case you can save them in a dictionary and have a wrapper function to merge them up whenever needed , else plot them individually – Vaebhav Jun 24 '21 at 05:00