0

I'm working on a code that exports data from Google Sheets and includes graphical representations. I've successfully generated the visualizations using Plotly in Python, and they display properly in my web browser for manual download. However, I'm attempting to automate this process using the static image export feature mentioned in the documentation.

I've encountered a problem where my code hangs during the image saving process. Although there are no errors or debug messages, the code gets stuck after generating the first graph. My script involves creating multiple graphs in a loop.

Any insights into why this might be happening would be greatly appreciated

for area, group_df in df.groupby('area'):

            fig = go.Figure()

            for cl_name in group_df["cluster_name"].unique():

                color_group = group_df[group_df["cluster_name"] == cl_name]

                trace = go.Scatter(
                    y=color_group["keyword"],
                    x=color_group["count"],
                    mode="markers",
                    marker=dict(
                        size=color_group["count"] / 15,
                        color=color_group["color"],
                        line=dict(
                            width=2,
                            color="grey"
                        )
                    ),
                    name=f"{cl_name}"
                )

                fig.add_trace(trace)

            text_scatter = go.Scatter(
                y = group_df["keyword"],
                x = group_df["count"],
                mode = "text",
                text = group_df["keyword"].apply(lambda x: x if len(x) < 15 else x[:5] + "\\" + x[-5:]),
                textposition='top center',
                showlegend = False
            )

            fig.add_trace(text_scatter)

            fig.update_layout(
                title = "Area - " + area,
                xaxis = dict(showgrid=False, showticklabels=False),    
                yaxis = dict(showgrid=False, showticklabels=False),     
                plot_bgcolor = "white",                                 
                annotations = [                                           # Footer
                    dict(
                        x=0.95,  
                        y=0.005,  
                        text= "Footer",  
                        showarrow=False, 
                        xref="paper",  
                        yref="paper",  
                        font=dict(size=24, color="gray")  
                    )
                ]
            )

            # Shows the graph
            fig.show()

            
            # Creates dir if it's doesn't exist
            if not os.path.exists("images"):
               os.mkdir("images")

            # Saves image
            *# Hangs HERE*
            fig.write_image(f"images/{area}.jpeg", width=800, height=600)

I initially tried debugging the code, but the process halts before any debug information is displayed. This problem persists regardless of whether I use VS Code or PyCharm as my IDE.

In an effort to identify the cause, I removed any additional traces from the generated graphics, thinking that they might be causing the hang. Unfortunately, this didn't have any effect on the problem. I even went as far as restarting my PC and reinstalling Python, but the issue remains.

I have noticed in debuging that MainThread is running, but Thread-6(_collect_standard_error), so that's it.

  • I used some dummy data, and i'm able to run your code and it saves one figure for each group in the dataframe. When you say you removed the traces, do you mean that your program hangs even when you only have `fig = go.Figure()` in the groupby loop? – Derek O Aug 29 '23 at 02:46
  • Yes, that's how it's work on my machine for some reason – Good Morning Aug 29 '23 at 12:01

1 Answers1

0

I found the answer. I couldn’t saw it for few days, but it exists.

Not able to save plotly plots using to_image or write_image [duplicate] I think this one better then original.

Basically, you should install this version of kaleido:

pip install kaleido==0.1.0post1

And you need to add one more parameter 'format=' added in write_image() like this:

fig.write_image(f"images\{area}.png", format='png', width=1500, height=1500)