9

For most of my interactive plotting with matplotlib, I don't want to use latex processing of math. (Mostly because it's too slow, but also because it's just that little bit too blurry for frequent use IMHO.) But I also use my own macros all the time when writing latex. As just one example, rather than doing something like $M_{\odot}$ I define $\Msun$. So when using matplotlib, I have a tendency to just write the latter automatically, and then get an error and have to fix it. This is just one particularly simple example, and I'd like to have the flexibility to redefine a macro in my papers and my plots simultaneously without too much work.

So, is there any reasonably nice way I could extend the mathtext parser to understand things like $\Msun$? Or would I have to hack mathtext.py or something?

(My fallback is defining Msun as the string r'M_{\odot}' so I could write something like r'$M = 10\,' + Msun + '$', but that's unpleasant and certainly wouldn't be any more automatic for me.)

Mike
  • 19,114
  • 12
  • 59
  • 91

2 Answers2

4

Macros are not supported by matplotlib's mathtext, you'd have to edit mathtext.py. Maybe the easiest thing to do is to do your own macro expansion before passing the string to the mathtext parser, e.g. text(x,y,expand(r'$M = \Msun$')) where expand replaces your own macros such as \Msun with its meaning.

Jouni K. Seppänen
  • 43,139
  • 5
  • 71
  • 100
  • 1
    And to save on writing effort, you could make your own 'text' function which first calls 'expand' and then passes the results to matplotlib's 'text'. Now you simply call mike.text(x,y,'$\Msun$') or whatever other latex macro you like. – Daan Feb 14 '12 at 08:51
  • Yeah, this should work. Moreover, because I just use `ipython --pylab` anyway, I think I can `del text`, then import `mike.text`, which will call `matplotlib.pyplot.text` -- and similarly for `xlabel`, `ylabel`, etc. (Though I'm a python newbie, so please correct me if that's stupid.) Thanks! – Mike Feb 14 '12 at 16:20
0

You can add your latex \newcommands into the preamble, like here: Matplotlib latex working directory / search path

Community
  • 1
  • 1
ev-br
  • 24,968
  • 9
  • 65
  • 78
  • But this is for when I specifically _don't_ want to use tex processing (`rcParams['text.usetex']=False`), so the latex preamble doesn't get used. – Mike Feb 13 '12 at 14:54