mkrphys / ipython-tikzmagic

IPython magics for generating figures with TikZ
BSD 3-Clause "New" or "Revised" License
160 stars 44 forks source link

Passing value of python variable to tikz #11

Open runningopenloop opened 7 years ago

runningopenloop commented 7 years ago

I'm new to tikz and not experienced with iPython.

I was hoping to generate an image to display the locations of some calculated circles based on other code. However it does not appear to be possible? I guess the issue is at line 301 in tikzmagic.py where code is added (tex.append(code)), the code would need to be parsed and replacing variable names with variable contents? \begin{tikzpicture}[scale=%(scale)s] ''' % locals())

    tex.append(code)

    tex.append('''

\end{tikzpicture} \end{document} ''')

runningopenloop commented 7 years ago

I'm sure there is a better way to do this, but this has got me going. Also, not knowing tikz, I'm not sure if sandwiching my variable names between $ is a good idea. E.g. $myvar$

    replacements = re.findall("\$.+?\$", code)
    replacements2 = []
    for x in replacements:
        if x[1:-1] not in replacements2:
            replacements2.append(x[1:-1])

    ipy = get_ipython()

    for x in replacements2:
        code = re.sub("\$" + x + "\$", str(ipy.ev(x)), code)

    tex.append(code)
mkrphys commented 7 years ago

I wonder if this could be accomplished more immediately using string interpolation as it became available in Python 3.6?

make-github-pseudonymous-again commented 6 years ago

Any progress on that? What is currently the easiest way to display some tikz string outputed by a python function? Like

mytikzstring = x.tikz()
%%tikz
mytikzstring
mkrphys commented 6 years ago

There is not much progress on the original problem, however, your problem is easy to solve. Python variables can be passed in parameters, but not in the body of a TikZ cell. That is, what you can do is define a string, e.g., by

tikz_str = """
\draw[fill=red] (0,0) rectangle (1,1);
"""

or by your function, and then have a one-line %tikz cell, i.e.,

%tikz $tikz_str

That should do what you want.

make-github-pseudonymous-again commented 6 years ago

Thanks I will try it out!