Save a "ggplotly" object from R in Json and then read it as plotly object in python

Hello,
I have some plots that created by ggplot library in R, and I use the ggplotly function to convert it into ggplot objects.
Is there is a way to save these objects as a json file, so I could open then later using plotly module in python (I want to build a dash app in python and use that plots).

So far I tried this code in order to generate the json in R:

library(ggplot2)
library(plotly)
library(jsonlite)
df <- read.csv("table.csv")
plot <- ggplot(df) + geom_point(mapping = aes(x = X, y = Y, colour = Co, text = X))
plot_ly <- ggplotly(plot)

plotly_json <- toJSON(plot_ly, pretty = TRUE)
json_file <- "test_plotly.json"
writeLines(as.character(plotly_json), json_file)

And this code in python order to open it

import plotly.graph_objects as go
import json

# Load the JSON file
json_file = "test_plotly.json"
with open(json_file, "r") as file:
    plotly_json = json.load(file)
# Create a plotly figure from the loaded JSON
loaded_plot = go.Figure(plotly_json)
loaded_plot.show()

But it didn’t manage to load the json file. Thank you so much!

Hey @gilmahalla , welcome to the community.

You are doing this, because you can’t create the plot in plotly dash, I suppose. What does the plot look like?

Thank you @AIMPED ,
I have a large number of complex plots that were created by ggplot in R, Some of them are scatter plot with some density features, histograms with fit function above it and more…
Unfortunately, due to time constraints I’m currently unable to refactor these graphs and recreate them using plotly.
I successfully coverted all these plots into plotly objects using “ggplotly” function, And I’m hopping to find a way to save these objects as json files, so I could reopen them in python and add them as plotly objects into my dash app.
Do you think this is possible?

Interesting. I never tried. Could you provide a sample Json file? One with pretty=True and one with pretty=False?

1 Like