python matplotlib axis label subscript based on loop counter - python

I'm using python and matplotlib to generate graphical output.
I am creating multiple plots within a loop and would like the loop counter to serve as an index on the y-axis label. How do I get the loop counter (a variable) to appear as a subscript?
Here's what I have:
axis_ylabel = plt.ylabel(u"\u03b1 [\u00b0]", rotation='horizontal', position=(0.0,0.9))
resulting in:
α [°]
(I'm using unicode instead of Tex because dvipng is not available on this system.)
I would like something like this:
for i in range(1,3):
axis_ylabel = plt.ylabel(u"\u03b1" + str(i) + u" [\u00b0]", rotation='horizontal', position=(0.0,0.9))
No surprise, this gives:
α1 [°]
α2 [°]
What I really want is the numbers to be subscripts. How do I combine the conversion to a string with a command to create a subscript? Including a '_' is not recognized in the unicode environment to generate a subscript. Additionally, I still need python/matplotlib to recognize that this subscript-command should affect the following variable.
Any thoughts?
Edit
I got this far:
axis_ylabel = plt.ylabel(u"\u03b1" + r"$_" + str(i) + r"$" + u" [\u00b0]", rotation='horizontal', position=(0.0,0.9))
-- this results in a subscript character. However, it is NOT a conversion of the integer value but a different symbol.
Edit 2
I am using python 2.6.6 and matplotlib 0.99.1.1. Inserting any kind of string at <> in r"$<>$" will not result in the display of that string but an entirely different character. I have posted this issue as a new question.

Matplotlib ships its own mathematical expression engine, called mathtext.
From the documentation:
Note that you do not need to have TeX installed, since matplotlib
ships its own TeX expression parser, layout engine and fonts.
So maybe try to use the following:
for i in range(1,3):
plt.ylabel(
r"$\alpha_{:d} [\degree]$".format(i),
rotation='horizontal',
position=(0.0,0.9))
You can also use Unicode in mathtext:
If a particular symbol does not have a name (as is true of many of the
more obscure symbols in the STIX fonts), Unicode characters can also
be used:
ur'$\u23ce$'

Related

How to add newline symbol and multiplication symbol together in matplotlib

I am trynig to create a matplotlib label where I can use both newline symbol and multiplication symbol. However, when I use them together then I only see multiplication symbol with '\n' as a part of text. The code that i use to create the symbol is below.
r"L1+\nL1$\times$L2"
Can someone point where I am wrong.
Looks like the solution was easier than I thought. All I had to do was to make a string as a combination of individual strings like "L1+\n"+r'L1$\times$L2 and it works

Formatting string not working

I have done some research on formatting string but it does not want to work for me. I have this
for i in range(0,10):
stat = arr[i]
highscoreText = GameFont.render('{0:12}{1:>0}'.format(stat["Name"],stat["Score"]),2,(255,255,255))
Screen.blit(highscoreText,[50,50 + (i*30)])
Output: http://prntscr.com/b9abfw
The name works but I can't seem to make the Score align to the right.
The string formatting works as expected. Try to print formatted sting in console. The problem with the font you use. See, ll in hello take the same span as k below.
To solve this you have to render names and scores separately and then blit them at appropriate positions.
Or you can change the font you use to a monospace, like Courier or Dejavu mono
String formatting assumes that you are using a monospace font. Since you have decided to use a proportional font you will need to draw as separate blocks and use the graphics routines to align each block to the right.

Force LaTeX font to match default matplotlib font

I have seen this issue pop up here and there but have yet to find a suitable answer.
When making a plot in matplotlib, the only way to insert symbols and math functions (like fractions, exponents, etc...) is to use TeX formatting. However, by default TeX formatting uses a different font AND italicizes the text. So for example, if I wanted an axis label to say the following:
photons/cm^2/s/Angstrom
I have to do the following:
ax1.set_ylabel(r'Photons/$cm^2$/s/$\AA$')
This produces a very ugly label that uses 2 different fonts and has bits and pieces italicized.
How do I permanently change the font of TeX (Not the other way around) so that it matches the default font used by matplotlib?
I have seen other solutions that tell the user to manually make all text the same in a plot by using \mathrm{} for example but this is ridiculously tedious. I have also seen solutions which change the default font of matplotlib to match TeX which seem utterly backwards to me.
It turns out the solution was rather simple and a colleague of mine had the solution.
If I were to use this line of code to create a title:
fig.suptitle(r'$H_2$ Emission from GJ832')
The result would be "H2 Emission from GJ832" which is an illustration of the problem I was having. However, it turns out anything inside of the $$ is converted to math type and thus the italics assigned.
If we change that line of code to the following:
fig.suptitle(r'H$_2$ Emission from GJ832')
Then the result is "H2 Emission from GJ832" without the italics. So this is an example of where we can constrain the math type to include only the math parts of the text, namely creating the subscript of 2.
However, if I were to change the code to the following:
fig.suptitle(r'H$_{two}$ Emission from GJ832')
the result would be "Htwo Emission from GJ832" which introduces the italics again. In this case, and for any case where you must have text (or are creating unit symbols) inside the dollar signs, you can easily remove the italics the following way:
fig.suptitle(r'H$_{\rm two}$ Emission from GJ832')
or in the case of creating a symbol:
ax2.set_xlabel(r'Wavelength ($\rm \AA$)')
The former results in "Htwo Emission from GJ832"
and the latter in "Wavelength (A)"
where A is the Angstrom symbol.
Both of these produce the desired result with nothing italicized by calling \rm before the text or symbol in the dollar signs. The result is nothing italicized INCLUDING the Angstrom symbol created by \AA.
While this doesn't change the default of the TeX formatting, it IS a simple solution to the problem and doesn't require any new packages. Thank you Roland Smith for the suggestions anyway. I hope this helps others who have been struggling with the same issue.
For typesetting units, use the siunitx package (with mode=text) rather than math mode.
Update: The above is only valid when you have defined text.usetex : True in your rc settings.
From the matplotlib docs:
Note that you do not need to have TeX installed, since matplotlib ships its own TeX expression parser, layout engine and fonts.
And:
Regular text and mathtext can be interleaved within the same string. Mathtext can use the Computer Modern fonts (from (La)TeX), STIX fonts (with are designed to blend well with Times) or a Unicode font that you provide. The mathtext font can be selected with the customization variable mathtext.fontset
Reading this, it sounds that setting mathtext.fontset and the regular font that matplotlib uses the same would solve the problem if you don't use TeX.

Reading LaTeX expression and pretty printing it as ASCII with python

I'm running some python code in the terminal and I want to output a pretty ASCII representation of a LaTeX expression. I realize I can pop up a separate window using matplotlib, but I don't want the text in a separate window. Sympy does a nice job printing, but doesn't seem to import LaTeX (at least not that I've found).
Ideally, It would work something like this:
print('$x^2$')
would output in the console:
2
x
Just like sympy would if I made a sympy symbol x and printed x**2.
More complicated expressions would have to be handled appropriately. For example:
\lim_{n \to \inf} \sum_{x=1}^{n} \frac{1}{x}
could be rendered as:
n
-----
\ 1
lim > -----
n->inf / x
-----
x=1
Characters which are not supported in ASCII such as $\alpha$ could be expanded to an ASCII equivalent such as "alpha" or an error could be thrown.
LaTeX parsing is not currently included in SymPy, although it has been speculated since 2012 with a decently high priority.
The third-party latex2sympy may be able to fulfill your needs.

Matplotlib LaTeX: Inconsistent Behaviour with Greek Letters (Specifically \rho)

I'm trying to add some axis-labels to a graph which contains the Greek letter 'rho'. To do this I want to use the LaTeX capability of Matplotlib but it seems to have a problem with the \rho symbol.
Here is a minimal example:
import matplotlib.pyplot as plt
from matplotlib import rc,rcParams
rc('text',usetex=True)
rcParams.update({'font.size': 16})
plt.plot([0,1,2,3,4],[0,1,4,9,16])
plt.xlabel('\rho A_i') # works if \rho is replaced with, for example, \sigma
plt.ylabel('Something else')
plt.show()
Upon running the first time I get a bunch of LaTeX errors and a blank figure window, running again shows the graph but the xlabel reads 'ho Ai ' where the i is subscript as expected.
The weird thing is if I replace \rho with something else, say, \sigma it shows up correctly. Can anybody tell me why it is not happy with my code example and how to fix it?
Thanks.
P.s. I tried putting the expression in $..$ but that changed nothing.
I think you are supposed to use raw strings, and use the $ signs as well. Try:
plt.xlabel(r'$\rho A_i$')
Be careful when you're using \n , \r and so on in a string. Those are commands for e.g. entering a new line etc.
https://docs.python.org/2/library/re.html
To make sure you don't use these regular expression operators put \\rho instead of \rho.

Categories

Resources