Serialization of graph objects

I know this is not exactly what you are asking for but if your chart can be made to be html you could make it an Anvil Media object and store it in a DataTable. I do this sometimes when I need to store a chart. On the client side I display the chart in an iframe custom component.

In terms of getting Anvil’s Plotly component to consume a chart made elsewhere, I’m not sure but there probably is a way. In the Altair plotting package, the charts emit a JSON schema that defines the entire chart, and so that can be passed around easily. I’m unsure if Plotly does something similar but other Plotly users here can likely help.

Once you have the chart how you like it in Colab, could you not just copy over the Plotly code to Anvil and render it there? I’m just trying to understand the reason why the Plotly code can’t be moved to Anvil (assuming the Plotly chart is compatible with Anvil’s Plotly version).

Good luck and I’m sure other Plotly users here can help.


Edit:

I managed to serialize a plotly chart in Colab using cloudpickle (also available in Anvil). From there the chart can be stored in a DataTable, unpickled, returned to the client, and consumed by the Plotly component as follows:

In Colab:

pip install chart-studio

import cloudpickle
import chart_studio.plotly
import plotly.graph_objs as go

data = [go.Bar(
            x=['giraffes', 'orangutans', 'monkeys'],
            y=[20, 14, 23]
    )]

with open('filename.pickle', 'wb') as handle:
    cloudpickle.dump(data, handle, protocol=cloudpickle.DEFAULT_PROTOCOL)

In Anvil Server:

import cloudpickle
from urllib.request import urlopen

@anvil.server.callable
def get_chart_obj():
  
  chart = app_tables.chart_obj.get(name='chart')['chart']
  chart = cloudpickle.load(urlopen(chart.url)) 
  
  return chart

In Anvil Client:

chart=anvil.server.call('get_chart_obj')
self.plot_1.data=chart

Bam, there’s the chart:

Here is a clone of the app:
https://anvil.works/build#clone:WU5ZDAV5CQEPEKRH=HDJKZTYOS5CGHZF3DARFXZLT

5 Likes