Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending the matplotlib mathtext parser

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.)

like image 632
Mike Avatar asked Feb 12 '12 21:02

Mike


1 Answers

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.

like image 82
Jouni K. Seppänen Avatar answered Nov 04 '22 17:11

Jouni K. Seppänen