Altair chart save only the data to html that is actually part of the plot

Viewed 25

When creating a chart using altair, I like the fact that I can save it to .html containing all the data in the plot. However, also the columns of a pd.DataFrame that are not plotted are stored in the .html file.

I am in a situation, where my data frame has roughly 100 columns but only ~5 of them are part of the plot. Thus I'd like to be able to only save those columns in the plot that are actually used, decreasing the file size of the .html by a factor 20.

Here's an MWE:

import numpy as np
import pandas as pd
import altair as alt

mwe_df = pd.DataFrame(
    {
        "x": np.arange(10),
        "y": np.random.randn(10),
        "z": np.random.randn(10),
    }
)

chart = alt.Chart(mwe_df).mark_line().encode(
    x="x",
    y="y"
)
chart.save("mwe.html")

The resulting file mwe.html looks like this

<!DOCTYPE html>
<html

// I cut a lot of code away to show the important part

<body>
  <div id="vis"></div>
  <script>
    (function (vegaEmbed) {
        
        // I cut a lot of code away to show the important part

        "datasets": {
          "data-f268207ac55fefac2d4e472cf850ebe3": [{
            "x": 0,
            "y": 0.5499788508261615,
            "z": -1.477946005772743 // Don't want this here
          }, {
            "x": 1,
            "y": 0.6200551442726329,
            "z": 0.857375723129614 // Don't want this here
          }, {
            "x": 2,
            "y": 2.162997199610359,
            "z": 0.8528682789795423 // Don't want this here
          }, 

        // I cut a lot of code away to show the important part
</body>

</html>

I could of course only hand a subset of the data frame to altair, i.e. by calling alt.Chart(mwe_df[["x","y"]]) but this seems a bit cumbersome.

Is there a way to tell altair to only save the relevant columns in the .html?

1 Answers

I also think this would be a useful feature to have in Altair, but there are some considerations with implementing it. You can follow preliminary work and discussion in this PR https://github.com/altair-viz/altair/pull/2586. In addition of what is mentioned there, it is possible that something might be offered via VegaFusion (https://vegafusion.io/) in the future as it covers some of the same things as the altair_transform package.

Related