Force LaTeX font to match default matplotlib font - python

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.

Related

How can I put giant writing in Python?

How could I make a word in giant text (for example “welcome” but giant)? I know that it's possible to change the console to make the font larger but I need it for just the word.
There are 2 ways to solve this problem
1 - Change the font in the python shell. Go to configure IDLE , go to the fonts tab and change the size value. Then apply the changes
2 - Using ASCII art. You can use ASCII art generators or use the python package pyfiglet(python version of figlet).
Example with pyfiglet
import pyfiglet
result = pyfiglet.figlet_format("Hello World")
print(result)
Pyfiglet also allows you to use many fonts , you can read their documentation for the everything else.
Hope this helps :)

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.

Aligning strings in Python

I searched for creating aligned strings in Python and found some relevant stuff, but didn't work for me. Here's one example:
for line in [[1, 128, 1298039], [123388, 0, 2]]:
print('{:>8} {:>8} {:>8}'.format(*line))
Output:
1 128 1298039
123388 0 2
This is what I see in the shell:
As you can see, the alignment didn't happen. Same problem arises when using \t.
What can I do to align the strings in a neat, tabular format?
You have configured your IDLE shell to use a proportional font, one that uses different widths for different characters. Notice how the () pair takes almost the same amount of horizontal space as the > character above it.
Your code is otherwise entirely correct; with a fixed-width font the numbers will line up correctly.
Switch to using a fixed width font instead. Courier is a good default choice, but Windows has various other fonts installed that are proportional, including Consolas.
Configure the font in the Options -> Configure IDLE menu. Pick a different font from the Font Face list. The sample characters in the panel below should line up (except for the second line k at the end, it should stick out).

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.

Non-ASCII characters in Matplotlib

I have a problem displaying non-ASCII characters in Matplotlib, these characters are rendered as small boxes instead of a proper font, it looks like (I filled these boxes with red paint to hightlight them):
How do I fix it?
A related question is Accented characters in Matplotlib.
This problem may actually have a couple of different causes:
The default font does not include these glyphs
You may change the default font using the following (before any plotting is done!)
matplotlib.rc('font', family='Arial')
In some versions of matplotlib you'll have to set the family:
matplotlib.rc('font', **{'sans-serif' : 'Arial',
'family' : 'sans-serif'})
(Note that because sans-serif contains a hyphen inside the **{} syntax, it is actually necessary.)
The first command changes the sans-serif font family to contain only one font (in my case it was Arial), the second sets the default font family to sans-serif.
Other options are included in the documentation.
You have improperly created/passed string objects into Matplotlib
Even if the font contains proper glyphs, if you forgot to use u to create Unicode constants, Matplotlib will have this behaviour:
plt.xlabel("Średnia odległość między stacjami wsparcia a modelowaną [km]")
So you need to add u:
plt.xlabel(u"Średnia odległość między stacjami wsparcia a modelowaną [km]")
Another cause is that you forgot to put a UTF-8 magic comment on top of the file (I read that this might be the source of the problem):
# -*- coding: utf-8 -*-

Categories

Resources