Errors when return plotly figure object from server through uplink

What I’m trying to do:
Free account, try to use uplink on my own computer to return a plotly figure object to the client

    @anvil.server.callable
    def px_test():
        df = px.data.iris()
        fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")
        return fig

On the client side

    def button_1_click(self, **event_args):
        self.plot_1.figure = anvil.server.call('px_test')

What I’ve tried and what’s not working:
Error like below.
anvil.server.SerializationError: Cannot serialize return value from function. Cannot serialize <class ‘plotly.graph_objs._figure.Figure’> object at msg[‘response’]

I am using a free account, is that the reason?

Hello and welcome,

Not all objects can be directly passed from server to client.

Please see this post on serializing plotly chart. There may be more information on the forum as well.

1 Like

Thanks for sharing the link. I have figured out how to deal with it properly. The logic is

  1. save your figure to json from your local server by fig.to_json()
  2. pass the json to client by a function call
  3. give the value of data and layout separately by self.plot_1.data = json.loads(resp)[‘data’] and self.plot_1.layout = json.loads(resp)[‘layout’] and it will work.

I wish one day Anvil will make plotly.io.from_json and go.Figure available on the client side.

Yes, indeed json/dict can be passed between server and client. Feature requests are welcome on the feature request channel. Glad you got it working.

A post was merged into an existing topic: Error in plotting

This helped.

I had a heat map and I wanted to show it in Anvil.
This is what I did:

Local Code

fig1 = fig.to_json()

@anvil.server.callable
def show_fig1():
return fig1, json.loads(fig1)[‘data’] , json.loads(fig1)[‘layout’]

Anvil Code

def show_fig1(self, **event_args):
“”“This method is called when the Plot is shown on the screen”""
figure, data, layout = anvil.server.call(“show_fig1”)
self.fig1.figure = figure
self.fig1.data = data
self.fig1.layout = layout
pass

1 Like

@karstn08 thank you for sharing; just did this successfully;

however, my line color information isn’t being passed

I specify in the Local Code function
line=dict(color=’#fc3300’)

but get the default color

Any thoughts? @meredydd