altair icon indicating copy to clipboard operation
altair copied to clipboard

Introduce export methods like `Chart.to_***()`

Open mattijn opened this issue 2 years ago • 5 comments

Distilled from https://github.com/altair-viz/altair/pull/3081#issuecomment-1587291370:

Currently we can export Altair specifications as such:

  • .save(format=***)
  • .to_dict(format=***) # defaults to vega-lite option for vega
  • .to_json(format=***) # defaults to vega-lite option for vega

Personally, I like it when there is a grouping using to_***(). Using the autocomplete I can discover what this object can be evaluated into (similar to autocomplete on .mark_***() and transform_***() to see what is possible).

For example:

  • to_svg()
  • to_png()
  • to_pdf(()
  • to_df()
  • to_pl()
  • to_arrow()
  • to_vgjson()
  • to_vljson()
  • to_json() # is vega-lite
  • to_vgdict()
  • to_vldict()
  • to_dict() # is vega-lite

mattijn avatar Sep 13 '23 21:09 mattijn

A convention we used in plotly that I still like is to use to_* for methods that return the converted object and write_* for methods that write the converted object to a file (or file-like object). So chart.write_png("chart.png") would write the png data to a file and chart.to_png() would return a bytes object with the encoded PNG data.

jonmmease avatar Sep 13 '23 22:09 jonmmease

BTW, are you picturing that to_df/to_pl/to_arrow would use the transformed_data logic?

jonmmease avatar Sep 14 '23 10:09 jonmmease

After re-reading my comment in the linked issue, I think that was indeed what I had in mind at that time. Not sure if it still make sense.

Regarding to_**()/write_**(). I think I prefer a single entrypoint using to_**(). And then use an argument check (eg. fp=None) to return a (byte)string in Python or write a file on disk.

Single entry, easy to remember, easy to maintain.

mattijn avatar Sep 14 '23 12:09 mattijn

Personally, I too have a (weak) preference for keeping separate nomenclature for methods that write to files vs those that return an object. So my vote here would be to keep the current naming with .save for those that write to a file (but could be convinced otherwise).

joelostblom avatar Sep 14 '23 18:09 joelostblom

When looking to the current code base it make sense to keep the .save() method to save chart definitions to different formats.

Also with the current code base we have introduced a new .to_url() method that returns a string and open_editor() function that opens a webbrowser.

Apparently we still have the to_html() that returns a string.

Based on the discussion above, I'm fine with the approach that the .to_**() methods returns the converted object and the .save() method, saves the converted object to file.

mattijn avatar Apr 08 '24 17:04 mattijn