word-cloudtag-cloudvegavega-litealtair

Creating wordclouds with Altair


How do I create a wordcloud with Altair? Vega and vega-lite provide wordcloud functionality which I have used succesfully in the past. Therefore it should be possible to access it from Altair if I understand correctly and I would prefer to prefer to express the visualizations in Python rather than embedded JSON. All the examples for Altair I have seen involve standard chart types like scatter plots and bar graphs. I have not seen any involving wordclouds, networks, treemaps, etc.

More specifically how would I express or at least approximate the following Vega visualization in Altair?

def wc(pages, width=2**10.5, height=2**9.5):
 return {
  "$schema": "https://vega.github.io/schema/vega/v3.json",
  "name": "wordcloud",
  "width": width,
  "height": height,
  "padding": 0,
  "data" : [
      {
          'name' : 'table',
          'values' : [{'text': pg.title, 'definition': pg.defn, 'count': pg.count} for pg in pages)]
      }
  ],
  "scales": [
    {
      "name": "color",
      "type": "ordinal",
      "range": ["#d5a928", "#652c90", "#939597"]
    }
  ],
  "marks": [
    {
      "type": "text",
      "from": {"data": "table"},
      "encode": {
        "enter": {
          "text": {"field": "text"},
          "align": {"value": "center"},
          "baseline": {"value": "alphabetic"},
          "fill": {"scale": "color", "field": "text"},
          "tooltip": {"field": "definition", "type": "nominal", 'fontSize': 32}
        },
        "update": {
          "fillOpacity": {"value": 1}
        },
      },
      "transform": [
        {
          "type": "wordcloud",
          "size": [width, height],
          "text": {"field": "text"},
          #"rotate": {"field": "datum.angle"},
          "font": "Helvetica Neue, Arial",
          "fontSize": {"field": "datum.count"},
          #"fontWeight": {"field": "datum.weight"},
          "fontSizeRange": [2**4, 2**6],
          "padding": 2**4
        }
      ]
    }
  ],
}

Vega(wc(pages))

Solution

  • Altair's API is built on the Vega-Lite grammar, which includes only a subset of the plot types available in Vega. Word clouds cannot be created in Vega-Lite, so they cannot be created in Altair.