Save interactive plotly plot in HTML or another way

Viewed 668

I have built this interactive plot that I would like to save to HTML. This is the code I used to build it.

def vis_pcs(M, a, b, label='album', prefix='PC', symbol=None):
    fig = px.scatter(M, prefix + str(a), prefix + str(b), 
                        color=label,
                        hover_name='album',
                        hover_data=['genre', 'song_title'],
                        marginal_x='box',
                        symbol=symbol,
                        height=1000)
    fig.show()


I'm unsure how to save it I've used the following lines of code to save it but each throws an error:

fig.write_html(data_path+"/genre.html")
import plotly.io as pio
pio.write_html(fig, file=data_path+"/genre.html", auto_open=True)
plotly.offline.plot(fig, filename= data_path+"/genre.html")

Any help would be appreciated as for data to reproduce the graph its difficult to give but its a scatterplot

1 Answers

Based on the error 'NoneType' object has no attribute 'write_html', the variable fig is being set to a 'NoneType' object.

Currently your function doesn't return anything, so if you are setting fig using your vis_pcs function, fig = vis_pcs(...), this will set fig to a NoneType object. In Python, a local variable is only available inside of a function because of scope rules.

To resolve this, you can add a return statement to your function:

def vis_pcs(M, a, b, label='album', prefix='PC', symbol=None):
    fig = px.scatter(M, prefix + str(a), prefix + str(b), 
                        color=label,
                        hover_name='album',
                        hover_data=['genre', 'song_title'],
                        marginal_x='box',
                        symbol=symbol,
                        height=1000)

    ## add a return statement
    return fig

Then set the variable fig to the figure that your function returns:

fig = vis_pcs(...)

After that you should be able to access the write_html attribute for Plotly figures and fig.write_html(data_path+"/genre.html") should work.

Related