简体   繁体   中英

Using equations (with symbols) in matplotlib legend

I was trying to use equations in the matplotlib legend, it is showing me the following error:

---------------------------------------------------------------------------
ParseFatalException                       Traceback (most recent call last)
/srv/conda/envs/notebook/lib/python3.6/site-packages/matplotlib/mathtext.py in parse(self, s, fonts_object, fontsize, dpi)
   2580         try:
-> 2581             result = self._expression.parseString(s)
   2582         except ParseBaseException as err:

/srv/conda/envs/notebook/lib/python3.6/site-packages/pyparsing.py in parseString(self, instring, parseAll)
   1954                     exc.__traceback__ = self._trim_traceback(exc.__traceback__)
-> 1955                 raise exc
   1956         else:

/srv/conda/envs/notebook/lib/python3.6/site-packages/matplotlib/mathtext.py in unknown_symbol(self, s, loc, toks)
   2751         c = toks[0]
-> 2752         raise ParseFatalException(s, loc, "Unknown symbol: %s" % c)
   2753 

ParseFatalException: Unknown symbol: \DeltaG, found '\'  (at char 0), (line:1, col:1)

-----[snip]-----

ValueError: 
\DeltaG_0 = 1
^
Unknown symbol: \DeltaG, found '\'  (at char 0), (line:1, col:1)

What is the issue in the following code?

import numpy as np
import matplotlib.pyplot as plt


fig = plt.figure()
lines = plt.plot(range(10), np.random.randn(10), range(10), np.random.randn(10), range(10), np.random.randn(10))
plt.legend([r'$\DeltaG_0 = 1$',r'$\DeltaG_0=2$',r'$\DeltaG_0=3$'])

plt.show()

I need the upper case Delta symbol($\Delta$) in my legend.

Also, is there anyway to reduce the following expression to something like 3*[np.random.randn(10), range(10)]??

plt.plot(range(10), np.random.randn(10), range(10), np.random.randn(10), range(10), np.random.randn(10))

You can actually put delta directly in your code. Matplotlib supports it. You can also just use a for loop for your second question.

import numpy as np
import matplotlib.pyplot as plt


fig = plt.figure()
for _ in range(3):
    plt.plot(range(10), np.random.randn(10))
plt.legend([r'$ΔG_0 = 1$',r'$ΔG_0=2$',r'$ΔG_0=3$'])

plt.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM