Because of a long calculation time required to create plots that I have, I want to store the plot output in the database so that I can immediately display the chart again without recalculation.
I have been using a simple object column - on retrieval from the database the chart is not displayed as the format of what is stored is different to the original saved. There is a prefix {‘type’: ‘plotly.graph_objs.Scatter’ and the formatting of the data is different - see images below
Your initial screen shot is incomplete. It ends before the data does. If you look at your complete listing, you’ll probably find the type entry near the bottom.
Notice that, in your original listing, whitespace and other formatting is inserted between data elements. It may aid readability, but it is not part of the data itself.
A SimpleObject, to save space and time, stores (and retrieves) only the actual data. The formatting is left out. dict keys are unordered, so may be recorded in a different order.
You might use module pprint (pretty-print) (or some similar tool) to format the printout to your liking.
Edit: If you need to preserve the format of the original text, you could use a Text column instead.
Depending on how you are doing it Plotly has a to_json and write_json methods. So you should be able to use json_object = plotly.io.to_json(fig, 'name.json').
Your initial idea is correct in that Plotly really is JSON underneath. But the straight Plotly object is really a JSON wrapper.
Many thanks I’ll give it a try although I am not using fig in plotly but using self.plot_1.data = scatter to display charts. scatter is the variable that holds the plotly go(scatter)
Many months ago you helped me with storing plotly json data. Much appreciated
I am trying to save an image of the plot in the database so that I can email it. I see there is a plotly.io functtion for this but how do you import plotly.io into Anvil works? Do you know of another means of doing this?
Assuming you had the JSON stored in the data table, you can load the JSON back into plotly as so:
Server Code
import plotly
from anvil.tables import app_tables
@anvil.server.callable
def load_plot():
# some way to get it from the data table. obviously change as needed
plot_json = app_tables.some_table.get(name='awesome plot')['json']
fig = plotly.io.from_json(json)
return fig
Code is sorta pseudo code and I haven’t tested this. But it should generally work.
For large plots this can take a while due to the dict size. What I do in that case is convert the plot to HTML and load it in an iframe. It saves some time.
Thanks for this. I have tried out what you have suggested but plotly.io is not recognised by anvil works on the individual plan, so I am stuck I think. Any other ways??
Are you executing your code in the client or the server? The Plotly IO package is only available in the Python API, which is only available on the server side.