By default, in the upper right corner of each Altair chart, there is a dropdown menu with various options. This menu comes with Vega-Embed, the package used under the hood to render the charts.
The Vega-Embed menu can be customized differently for each chart. For this example, we will define a menu with only the options to export the chart as PNG or SVG. Also, the default name of the generated file will be "bar_chart" instead of "visualization", and we will increase the resolution for the PNG image. So, let's see how we can do it using the properties()
method and the usermeta
argument!
First of all, let's define a dictionary with all the necessary metadata:
metadata = {
"embedOptions": {
"actions": {
"export": True,
"source": False,
"compiled": False,
"editor": False,
},
"i18n": {"SVG_ACTION": "Export as SVG", "PNG_ACTION": "Export as PNG"},
"scaleFactor": 5,
"downloadFileName": "bar_chart",
}
}
To keep only the items to export
the chart, we start by removing the remaining ones (setting them to False
) from the menu. Second, we renamed these items to "Export as SVG" and "Export as PNG", respectively (i18n
). Third and fourth, specifically for exporting the chart as PNG, we changed the resolution scale factor from 1 to 5 (scaleFactor
) and chose "bar_chart" (without the file extension) as our new default filename (downloadFileName
). For more details on these items and other options, check the README file in the Vega-Embed repository.
Now, assuming we already have a chart (like the one in this example available in the Altair documentation), we pass the dictionary defined earlier as an argument to the properties()
method:
alt.Chart(source).mark_bar().encode(x="a", y="b").properties(usermeta=metadata)
If you want to adapt this example to a compound chart, make sure you use the properties()
method on the "final chart" and not on each of the "intermediate charts":
alt.hconcat(
alt.Chart(source).mark_bar().encode(x="a", y="b"),
alt.Chart(source).mark_bar().encode(x="a", y="b"),
).properties(usermeta=metadata)
Finally, if you have any questions or suggestions, feel free to leave a comment below!
Top comments (0)