To annotate my figures with Greek letters in the matplotlib package of Python, I use the following:
import matplotlib
matplotlib.use('PDF')
import matplotlib.pyplot as plt
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
plt.rcParams['ps.useafm'] = True
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
plt.rcParams['pdf.fonttype'] = 42
# plot figure
# ...
# annotate figure
plt.xlabel(r'$\mu$ = 50')
plt.ylabel(r'$\sigma$ = 1.5')
This makes the equal symbol and everything to the right of it in the Helvetica font, as intended, and the Greek symbols default to the usual TeX font (which I believe is Times New Roman.)
How can I make it so the font used for the Greek letters is the "Symbol" font instead? It's important for me not to have it appear in the default Times font of TeX.
thanks for your help.
Funny you should ask this; I've been struggling with similar problems not too long ago. Considering how complicated font handling is in TeX, I'd sidestep TeX altogether.
However, any decent Helvetica has the Greek letters built-in, so you don't need to use the Symbol font. Just put some Unicode code points into your string, like this:
plt.xlabel(u'\u03bc = 50')
plt.ylabel(u'\u03c3 = 1.5')
For finding the code points, this Unicode codepoint lookup/search tool is really convenient.
I'm not sure if and how matplotlib handles Unicode strings. If the above fails, encode in some encoding that matplotlib expects.
(If you really insist on using Symbol: I don't think you can use multiple fonts within the same label, so then you'll have to add multiple labels and write some code to align them to each other. It's not pretty, but it can be done.)
Related
I would like to print math in python with print(), as it is possible to do in plot's label with matplotlib (see this link for all the math you can write with matplotlib https://matplotlib.org/tutorials/text/mathtext.html )
Is that even possible ?
I tried the following (as in matplotlib):
print(r'$\Delta v$:', delta)
to print a greek delta for example, but it doesn't work (as it's not a matplotlib function), it shows : $\Delta v$: delta
You can actually print the characters with no issue in Python. Just find the associated unicode characters with a Google search and copy/paste them into your print statement.
print('Δ')
print('α')
No, it is generally not possible to do this using the print function - it just outputs plain text to standard output. matplotlib can render math text as, for instance, a plot title, because its target is the generated image.
Like Kurt Kline said, you can display simple characters, but not complex expressions like a sum symbol or superscripts.
When plotting data with units containing superscript or subscript (e.g. cm2), what is the best way to write the string?
I have tried unicode and mathematical expressions in Matplotlib, but it looks like the style of both does not match the rest of the string. The former character looks squeezed, and the latter looks too big. How can we display it beautifully?
For example:
Try putting your entire expression into the formatter, so rather than just formatting the "^2" format the entire thing "cm^2".
See the full tutorial here: https://matplotlib.org/3.1.1/tutorials/text/mathtext.html
You can adjust the mathtext font by using the rcParam mathtext.fontset. The supported options are 'dejavusans', 'dejavuserif', 'cm' (Computer modern), 'stix', and 'stixsans'. You can use this to match more closely the mathtext to the rest of your text.
Alternatively, you can use LaTex to perform the math display. You can enable this by setting thercParam text.usetex to True, but note that the strings may need to be raw by preceding the string with r, i.e.
r'$\text{cm}^2$'
Using LaTex will give you the most control, allowing you to directly adjust the size of the superscript or subscript directly via LaTex font sizing.
I need to put greek letters in labels of a matplotlib plot . how can I do it? For instance, unicode Omega is : u\u03A9. I use plt.xlabel('label')
If you are looking specifically for greek letter, you can use LaTex in-line math formatting commands (i.e. '$\Omega$') to produce letter that are in the Latex character map.
import numpy as np
import matplotlib.pyplot as plt
plt.plot(np.arange(1000), np.random.rand(1000), 'b.')
plt.xlabel('$\Omega$', size=16)
Here are good resources for finding LaTex symbols.
PDF list: https://www.rpi.edu/dept/arc/training/latex/LaTeX_symbols.pdf
Draw your symbol, get a bunch of LaTex characters: http://detexify.kirelabs.org/classify.html
I'm not positive about matplotlib, but I would assume that declaring them as unicode strings should work
>>> print u'\u03A9'
Ω
I've been having this trouble for a long time whenever I want to render LaTeX for plot labelling and text, it works sometimes for some symbols but not others. For example in my script shown here generates the plot below:
from matplotlib import rc
plt.rc('text', usetex=True)
plt.plot(a_t,asol[:,0],label ='$\psi$')
plt.plot(a_t,rho,label ="$\rho/\rho_c$")
plt.xlabel(r"$\xi$",fontsize=15)
from matplotlib.legend_handler import HandlerLine2D
plt.legend(loc='upper left',prop={'size':12},numpoints=1)
I've tried other symbols, $\pi$ works okay but $\theta$ only shows "heta" without the t. I'm confused by why some symbols works for LaTeX and some don't.
Thanks!
Remember that certain characters in Python strings have special meanings, e.g. \r for carriage return, \t for tab. That's why you're only getting the strange results some of the time, since \p doesn't have a special meaning. So either make sure your backslashes are treated as literal backslashes by escaping them:
plt.plot(a_t,rho,label = "$\\rho/\\rho_c$")
Or use raw strings:
plt.plot(a_t,rho,label = r"$\rho/\rho_c$")
I'm trying to get a simple greek letter mu to display in roman font in a saved figure with matplotlib. I have tried two methods:
plt.xlabel(u'Wavelength (\u03bc m)')
This method works fine when I do a show(), but when I try to use savefig(), the mu character shows as a rectangle when saved as a .png. If I save as a .pdf, the symbol is missing entirely.
plt.xlabel(r'Wavelength ($\mathrm{\mu}$m)')
This method renders a greek letter with both show() and savefig(), but the character is still in italics in each case, despite requesting a roman font.
What's the trick?
I have very good experience with having all text (regular and math) beeing typeset by LaTeX. Just set your rc-settings accordingly before plotting:
import matplotlib.pyplot as plt
plt.rcParams['text.usetex'] = True #Let TeX do the typsetting
plt.rcParams['text.latex.preamble'] = [r'\usepackage{sansmath}',r'\sansmath']
#Force sans-serif math mode
plt.rcParams['font.family'] = 'sans-serif' # ... for regular text
plt.rcParams['font.sans-serif'] = 'Helvetica' # Choose a nice font here
You can then simply say:
plt.xlabel('Wavelength ($\mu$)')
Inspired by my own answer here:
Type 1 fonts with log graphs