I did not go through your code but I suspect you are doing exactly what is described here: Why do I get a `cannot reference context` error when referencing a custom figure? - #4 by bluss
I did not go through your code but I suspect you are doing exactly what is described here: Why do I get a `cannot reference context` error when referencing a custom figure? - #4 by bluss