No image show up on for loop

Viewed 249

I made a function which creates plotly figure and applied for loop on it.

def doplot(df, somenumber):
forplot = some_preprocessing_function(df,somenumber)
fig = px.line(forplot, x = 'STATS_DTTM', y = "FRME_DISTRICT_CODE",color = "FRME_MEDIA", line_group="FRME_MEDIA", hover_name="FRME_MEDIA", line_dash  = 'FRME_MEDIA')

return fig

When executing the function without for loop, the function successfully showed an image.

doplot(df,0)

After I checked the function generates an image, I tried for loop on it so that I can see the output images for different parameters.

for i in range(4):
    doplot(df,i)

The for loop fail to create any image. I found out that I missed fig.show() in my plotting function but I still cannot understand why even the last image did not show up. As I understand, the for loop is same as the code below.

doplot(df,0)
doplot(df,1)
doplot(df,2)
doplot(df,3)

and execution of above code results the output image of last code doplot(df,3).

If its about the for loop, can someone explain what I misunderstand about it?

Many thanks,

1 Answers

Can you try using plt.figure() in your doplot() function like:

#import matplotlib.pyplot as plt

def doplot(df, somenumber):
plt.figure()
forplot = some_preprocessing_function(df,somenumber)
fig = px.line(forplot, x = 'STATS_DTTM', y = "FRME_DISTRICT_CODE",color = "FRME_MEDIA", line_group="FRME_MEDIA", hover_name="FRME_MEDIA", line_dash  = 'FRME_MEDIA')

return fig

Let me know if it works for you.

Edit(Explanation): So what matplotlib does is it creates a new figure when you call it using plt.line() or any other plot function. When in for loop, it continues to override that same figure till the end of loop and thus you end up with only the final plot instead of multiple plots from for loop. That is the reason why I added plt.figure() in the function that will loop so it creates a new figure every iteration.

Related