Signing text in matplotlib tags

This is my first question, and I write in python. So probably more to follow ...

I would like to create a shape with matplotlib. In methods, I would like to include a chemical formula that includes indexes (I think the same will work for add-ons ...).

In any case, I have no idea what the label should look like.

import numpy as nu import pylab as plt x = nu.array([1,2,3,4]) y = nu.array([1,2,3,4]) plt.plot(x,y, label='H2O') plt.legend(loc=1) plt.show() 

Ok, this gives me a graph labeled โ€œH2Oโ€. How can I index โ€œ2โ€ in a label, as is usually the case with chemical formulas?

I searched on the internet but havenโ€™t found anything useful yet.

I realized that I can use

 from matplotlib import rc rc['text', usetex=True] 

but I donโ€™t want to use it (I know how to use LaTeX, but I donโ€™t want to here).

Another variant:

 label='H$_2$O' 

but that changes the font (math).

There must be a way how signatures work in matplotlib legends?

Thanks a lot!

+4
source share
1 answer

Try changing this line.

 plt.plot(x,y, label='H2O') 

for this:

 plt.plot(x,y, label='$H_2O$') 

It is displayed using the math font.

Or also you can use the Unicode character for this: โ‚‚ (0xE2 / โ‚‚)

 plt.plot(x,y, label=u'Hโ‚‚O') 

or instead:

 plt.plot(x,y, label=u"H\u2082O") 

Note that unicode strings are marked as u "instead of" ".

+2
source

Source: https://habr.com/ru/post/1486516/


All Articles