Home > Enterprise >  Matplotlib fails to render LaTeX table
Matplotlib fails to render LaTeX table

Time:05-23

I am trying to add this table to a plot:

enter image description here

Example Script:

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams['text.usetex'] = True

fig, ax = plt.subplots()

x = np.linspace(-10, 10)
ax.plot(x, x**2)

# adding table
table = r"""\begin{tabular}{cc}
\bf{Material} & \bf{Roughness ($\epsilon$)} \\
\midrule
Drawn Tubing & 0.000005 \\
Commercial Steel or Wrought Iron & 0.00015 \\
Asphalted Cast Iron & 0.0004 \\
Galvanized Iron & 0.0005 \\
Wood Stave & 0.0006-0.003 \\
Cast Iron & 0.00085 \\
Concrete & 0.001-0.01 \\
Riveted Steel & 0.003-0.03
\end{tabular}"""

ax.annotate(table, xy=(0, 60), ha='center', va='center')

plt.show()

The LaTeX syntax above is correct because I got the successful output in the above image. The above script fails with LaTeX not able to register the string stored in table. If I were to replace the string with r'\bf{Testing}', the script will run and output the following:

enter image description here

I'm lost because it the above example shows that matplotlib is able to handle the LaTeX, but not the tabular environment. I'm not too familiar with LaTeX, but I'm wondering if matplotlib doesn't automatically add some dependency to the preamble. This example is similar to this SO post, but it still won't work.

CodePudding user response:

The code is creating a multi line string (adding \n at the end of each line). If you run print(repr(table)), the output is:

'\\begin{tabular}{cc}\n\\bf{Material} & \\bf{Roughness ($\\epsilon$)} \\\\\n\\midrule\nDrawn Tubing & 0.000005 \\\\\nCommercial Steel or Wrought Iron & 0.00015 \\\\\nAsphalted Cast Iron & 0.0004 \\\\\nGalvanized Iron & 0.0005 \\\\\nWood Stave & 0.0006-0.003 \\\\\nCast Iron & 0.00085 \\\\\nConcrete & 0.001-0.01 \\\\\nRiveted Steel & 0.003-0.03\n\\end{tabular}'

You can construct a long raw line by using the ():

table = (r"\begin{tabular}{cc}"
r"\bf{Material} & \bf{Roughness ($\epsilon$)} \\"
r"\hline "
r"Drawn Tubing & 0.000005 \\"
r"Commercial Steel or Wrought Iron & 0.00015 \\"
r"Asphalted Cast Iron & 0.0004 \\"
r"Galvanized Iron & 0.0005 \\"
r"Wood Stave & 0.0006-0.003 \\"
r"Cast Iron & 0.00085 \\"
r"Concrete & 0.001-0.01 \\"
r"Riveted Steel & 0.003-0.03"
r"\end{tabular}")

Putting the leading "r" at every line, so that all portions are interpreted as raw (see here).

Furthermore, I had to replace the midrule by r"\hline ", as it was not recognised (package required?).

  • Related