Reputation: 992
matplotlib crashes when a Pandas Serie contains specific special chars in a string, in my case $$
.
import matplotlib.pyplot as plt
import random
import pandas as pd
list_= 'abcdefghijklmnopqrstuvwxyz'
l = pd.Series()
for i in range(0,100):
l[i] = random.choice(list_)
l[50] = '$$'
l.value_counts(normalize=False).plot(kind='bar')
plt.show()
This code will crash due to the l[50] = '$$'
line.
Question: am I expected to clean such strings beforehand, or is it a bug in matplotlib?
I'm fairly new to using python for data science, so bear with my naive approach.
Thanks
EDIT: thanks to @mozway and @chrslg for their answers, $$
is indeed interpreted as Latex by matplotlib and it raises an error because there's nothing between the two $
signs.
Having no control over the data I'm plotting, I've opted to deactivate the parsing of Latex by matplotlib like so:
plt.rcParams['text.parse_math'] = False
Upvotes: 0
Views: 55
Reputation: 262204
You need to escape the $
as it will be interpreted as LaTeX formatting (specifically, $...$
is the LaTeX math mode, which is useful if you want to type complex mathematical terms, try for instance l[49] = r'$x_1 \cdot \delta t$'
):
l[50] = r'\$\$'
l.value_counts(normalize=False).plot(kind='bar')
Output:
Upvotes: 5
Reputation: 13491
$$
is the beginning of a LaTeX math formula. So matplotlib crashes because you have a math formula opened and not closed.
Note that it did not crashes, strictly speaking. It correctly raises an error (it is not as if it broke the python interpreter with a segfault). The error message (that you should have included in your question) clearly states
ParseException: Expected end of text, found '$' (at char 0), (line:1, col:1)
(Well, not that clearly. But that is a very classical error for many parsers: it complains about what it expected)
Upvotes: 2