0

I am using LaTeX, Python and Pweave for the generation of dynamic reports. Panda to_latex and its option formatters allow me to include tables. But how could I set the table cell background color i.e. set cellcolor dynamically?

\documentclass[a4paper]{article}
\usepackage{booktabs}

\begin{document}
\section*{Tables with LaTeX and Pweave}

The table below list the names and ages of pupils. How can I dynamically generate LaTeX tables i.e. using the {\tt tabular}  LaTeX environment? I would like to set the table cell colour of {\tt age} with the innformation in {\tt age\_colour}.\\ \\

<<echo=False>>=
import pandas as pd

pupils = {'name':['Jeff','Lisa','Sam','Victoria'],'age':[26,34,6,68],'age_colour':['white','white','red','white']}

table = pd.DataFrame(pupils, columns = ['name', 'age'])
@

<<echo=False, results='tex'>>=
def f1(x):
  return str(x)

def f2(x):
  return '\cellcolor{\'red\'}{'+str(x)+'}'

print(table.to_latex(index=False, column_format='|l|c|', formatters=[f1,f2]))
@
3
  • Maybe you can use PyLaTeX jeltef.github.io/PyLaTeX/current
    – Alan Xiang
    Nov 25, 2020 at 15:33
  • @AlanXiang Tables in PyLaTeX are not supporting cell background colours. Guess it is a new feature request that needs to be implemented.
    – lars20070
    Nov 26, 2020 at 4:42
  • @Iars20070 But why can't you add \cellcolor command in the cell yourself? It's not terribly hard to do.
    – Alan Xiang
    Nov 26, 2020 at 6:46

1 Answer 1

0

I solved the problem by combining the value (age) and colour (age_colour) in a single column. Maybe there is another, more elegant solution.

\documentclass[a4paper]{article}
\usepackage{booktabs}
\usepackage{colortbl}

\begin{document}
\section*{Tables with LaTeX and Pweave}

The table below list the names and ages of pupils. How can I dynamically generate LaTeX tables i.e. using the {\tt tabular}  LaTeX environment? I would like to set the table cell colour of {\tt age} with the information in {\tt age\_colour}.\\ \\

<<echo=False>>=
import pandas as pd

pupils = {'name':['Jeff','Lisa','Sam','Victoria'],'age':[26,34,6,68],'age_colour':['white','white','red','white']}

# combine 'age' and 'colour' in a single column (then pass to formatter function f2)
table = pd.DataFrame(pupils, columns = ['name', 'age', 'age_colour'])
table['age'] = table['age'].astype(str) + '_' + table['age_colour'].astype(str)
table = table[['name', 'age']]
@

<<echo=False, results='tex'>>=
def f1(x):
  return str(x)

def f2(x):
  # split argument into 'age' and 'age_colour'
  split = x.split('_')
  age = split[0]
  colour = split[1]
  return '\cellcolor{'+str(colour)+'}{'+str(age)+'}'

print(table.to_latex(index=False, column_format='|l|c|', formatters=[f1,f2], escape=False))
@

\end{document}

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .