Black Lives Matter. Please consider donating to Black Girls Code today.

Returning an empty figure

Soo… here’s the issue:
I have a graph that takes data from my table, plays around with it a bit then displays, but sometimes this table is empty…

  • If i don’t address that, whenever the table is empty i get a KeyError , because none of the headers i have defined are there…
  • If i do this, the app breaks whenever the table is empty:
    def update_figure(data, value):
    try:
    #lots of code
    return figure
    except KeyError:
    pass
  • Same happens if i do this:
    def update_figure(data, value):
    if len(data!=0) :
    #lots of code
    figure = ...
    else:
    figure = {}
    return figure

Is there any other way around this?

Worth mentioning that i did not have an issue with this using a previous dcc version… i had the if-else condition, and it worked perfectly.

1 Like

I am not sure if it is the best solution, but maybe you could make a variable with some default values/headers which will be used if your data is empty.

Assuming your data is a list of lists with header, x and y:

def update_figure(data,value):
   if len(data!=0):
      pass
   else:
      data = ['Empty', [0], [0]]

      header = data[0]
      x = data[1]
      y = data[2]
      # do plot stuff ...

So basically you make a check if you have data, and if not, you feed your plotting routine with whatever you feel like will let the user know that the data is empty zero/nothing is plotted.

return {} should be the correct solution here. If this breaks things, then it’s a bug on our side. Thanks for reporting!

2 Likes

I have also run more or less into the same problem.
My solution was to return a dictionary with both data and layout fields with empty arrays.

Hope this helps.