Pyplot annotation: roman numerals - python

In a python plot, I would like to put annotations in with Roman numerals. I.e., "I", "II", "III" and "IV".
Now, the straightforward thing to do is to simply use strings as "I", "II", etc., but I would like them to be typeset specifically as Roman numerals (so, including the horizontal bar on top and below of the III, for instance.
The difficulty is mainly that using LateX commands, as I would do for other symbols (e.g. \alpha), doesn't seem possible because if one wants to use Roman numerals in LateX it is common practice to define a new command and I wouldn't know how to incorporate that within the python environment.
Any ideas?

This is possible, by placing your LaTeX \newcommand in the text.latex.preamble in plt.rcParams. Here I use the command for Roman Numerals from the answer you linked to. To help with the escaping of LaTeX characters, we can use raw strings to make thing easier (preface the string with the r character).
import matplotlib.pyplot as plt
# Turn on LaTeX formatting for text
plt.rcParams['text.usetex']=True
# Place the command in the text.latex.preamble using rcParams
plt.rcParams['text.latex.preamble']=r'\makeatletter \newcommand*{\rom}[1]{\expandafter\#slowromancap\romannumeral #1#} \makeatother'
fig,ax = plt.subplots(1)
# Lets try it out. Need to use a 'raw' string to escape
# the LaTeX command properly (preface string with r)
ax.text(0.2,0.2,r'\rom{28}')
# And to use a variable as the roman numeral, you need
# to use double braces inside the LaTeX braces:
for i in range(1,10):
ax.text(0.5,float(i)/10.,r'\rom{{{}}}'.format(i))
plt.show()

Related

What is the best practice to write units in superscript or subscript in Matplotlib?

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.

Plot special character as ① in matplotlib

I search the Internet, find nothing about typing special character like ① in matplotlib.
Is there code to represent the ‘①’ to display in the figure?
For now, I use:
## the ① character was found on the Internet, and I clipped it.
ax.text(0.425, 0.475, u'①', ha='center')
I think there must be some function to generate ①, ②, ③, ④ ...as a type of special character
The circled numbers start at Unicode code point 0x2460 and go up to 20. So just write a little helper function that returns the desired character:
def circled(x):
return chr(0x245F+x) # Python 2: use unichr() instead of chr()
Usage:
ax.text(0.425, 0.475, circled(1), ha='center')

LaTeX not working on matplotlib text

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$")

Printing subscript in python

In Python 3.3, is there any way to make a part of text in a string subscript when printed?
e.g. H₂ (H and then a subscript 2)
If all you care about are digits, you can use the str.maketrans() and str.translate() methods:
example_string = "A0B1C2D3E4F5G6H7I8J9"
SUB = str.maketrans("0123456789", "₀₁₂₃₄₅₆₇₈₉")
SUP = str.maketrans("0123456789", "⁰¹²³⁴⁵⁶⁷⁸⁹")
print(example_string.translate(SUP))
print(example_string.translate(SUB))
Which will output:
A⁰B¹C²D³E⁴F⁵G⁶H⁷I⁸J⁹
A₀B₁C₂D₃E₄F₅G₆H₇I₈J₉
Note that this won't work in Python 2 - see Python 2 maketrans() function doesn't work with Unicode for an explanation of why that's the case, and how to work around it.
The output performed on the console is simple text. If the terminal supports unicode (most do nowadays) you can use unicode's subscripts. (e.g H₂) Namely the subscripts are in the ranges:
0x208N for numbers, +, -, =, (, ) (N goes from 0 to F)
0x209N for letters
For example:
In [6]: print(u'H\u2082O\u2082')
H₂O₂
For more complex output you must use a markup language (e.g. HTML) or a typesetting language (e.g. LaTeX).
Using code like this works too:
print('\N{GREEK SMALL LETTER PI}r\N{SUPERSCRIPT TWO}')
print('\N{GREEK CAPITAL LETTER THETA}r\N{SUBSCRIPT TWO}')
The output being:
πr²
Θ₂
Note that this works on Python versions 3.3 and higher only. Unicode formatting.
If you want to use it on the axes of a plot you can do:
import matplotlib.pyplot as plt
plt.plot([1])
plt.ylabel(r'$H_{2}$')
plt.show()
which gives
By using this code you can use alphabets on the superscript and subscript
In This code
format() is Function and in Format function ('\unicode')
By using this table (Unicode subscripts and superscripts on Wikipedia) you can give suitable unicode to the suitable one
you can use superscript and sub script
"10{}".format('\u00B2') # superscript 2

using the symbol font for Greek symbols in TeX via matplotlib

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

Categories