我使用 LaTeX、Python 和 Pweave 生成动态报告。Pandato_latex
及其选项formatters
允许我包含表格。但我如何设置表格单元格背景颜色(即cellcolor
动态设置)?
\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]))
@
答案1
我通过将值 ( age
) 和颜色 ( age_colour
) 合并到一列中解决了这个问题。也许还有其他更优雅的解决方案。
\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}