Related
I'm using a MathJax in several projects and it generally works like a charm.
Today, however, I ran into a problem during the translation of a part of an existing LaTeX document with the following align-environment:
\begin{align}
& (\lambda x.(\lambda y.(\lambda z.xyz)))abc \\
= & \text{\{ impliciete toepassing expliciet maken \}} \\
& (((\lambda x.(\lambda y.(\lambda z.xyz)))a)b)c \\
= & \text{\{ \ensuremath{\beta}-reductie, substitutie van \ensuremath{x}door \ensuremath{a}\}} \\
& ((\lambda y.(\lambda z.ayz))b)c \\
= & \{\text{\ensuremath{\beta}-reductie, \ensuremath{y\,:=b}}\} \\
& (\lambda z.abz)c \\
= & \text{\{ \ensuremath{\beta}-reductie, \ensuremath{z\,:=c}} \\
& abc \\ \boxed{} \end{align}
The result rendered with LaTeX is this (sorry for the Dutch text ;-):
The align-environment is essentially a math context, so if you want text, you need to enclose that text with \text{...}. But when you need again math symbols within that text, you escape the text context by enclosing the maths with \ensuremath{...}.
And MathJax renders it like:
That Mathjax centers everything doesn't matter, that is something I can handle with CSS. But the rendering of \ensuremath is a problem. Clearly MathJax doesn't support \ensuremath, but I can't think of a workable workaround where I can use math symbols in a text-context.
Ideally I'ld like to have a solution using an alternative LaTeX construction (hence the cross listing)
Any ideas?
You should use $...$ or \(...\) in place of \ensuremath{...}. This seems more natural to me even in LaTeX itself (as \ensuremath is really designed for use within macros that might be used inside both text- and math-modes).
So you can do
\begin{align}
& (\lambda x.(\lambda y.(\lambda z.xyz)))abc \\
= & \{\text{ impliciete toepassing expliciet maken }\} \\
& (((\lambda x.(\lambda y.(\lambda z.xyz)))a)b)c \\
= & \{\text{ $\beta$-reductie, substitutie van $x$door $a$ }\} \\
& ((\lambda y.(\lambda z.ayz))b)c \\
= & \{\text{ $\beta$-reductie, $y:=b$ }\} \\
& (\lambda z.abz)c \\
= & \{\text{ $\beta$-reductie, $z:=c$ }\} \\
& abc \\ \boxed{} \end{align}
I also put the \{ and \} outside the \text{}, though you can do them inside if you prefer.
The centering is probably due to CSS on your page, as MathJax left-justifies these by default.
Is it possible to get a nicely formatted table from a pandas dataframe in ipython notebook when using nbconvert to latex & PDF?
The default seems to be just a left-aligned block of numbers in a shoddy looking font.
I would like to have something more like the html display of dataframes in the notebook, or a latex table. Saving and displaying a .png image of an HTML rendered dataframe would also be fine, but how exactly to do that has proved elusive.
Minimally, I would just like a simple centre-aligned table in a nice font.
I haven't had any luck with various attempts to use the .to_latex() method to get latex tables from pandas dataframes, either within the notebook or in nbconvert outputs. I've also tried (after reading ipython dev list discussions, and following the custom display logic notebook example) making a custom class with _repr_html_ and _repr_latex_ methods, returning the results of _to_html() and _to_latex(), respectively. I think a main problem with the nb conversion is that pdflatex isn't happy with either the {'s or the //'s in the dataframe to_latex() output. But I don't want to start fiddling around with that before checking I haven't missed something.
Thanks.
There is a simpler approach that is discussed in this Github issue. Basically, you have to add a _repr_latex_ method to the DataFrame class, a procedure that is documented from pandas in their official documentation.
I did this in a notebook like this:
import pandas as pd
pd.set_option('display.notebook_repr_html', True)
def _repr_latex_(self):
return "\centering{%s}" % self.to_latex()
pd.DataFrame._repr_latex_ = _repr_latex_ # monkey patch pandas DataFrame
The following code:
d = {'one' : [1., 2., 3., 4.],
'two' : [4., 3., 2., 1.]}
df = pd.DataFrame(d)
df
turns into an HTML table if evaluated live in the notebook, and it converts into a (centered) table in PDF format:
$ ipython nbconvert --to latex --post PDF notebook.ipynb
I wrote my own mako-based template scheme for this. I think it's actually quite an easy workflow if you commit to chugging through it for yourself once. After that, you begin to see that templating the metadata of your desired format so it can be factored out of the code (and doesn't represent a third-party dependence) is a very nice way to solve it.
Here is the workflow I came up with.
Write the .mako template that accepts your dataframe as an argument (and possibly other args) and converts it to the TeX format you want (example below).
Make a wrapper class (I call it to_tex) that makes the API you desire (e.g. so you can pass it your data objects and it handles the call to mako render commands internally).
Within the wraper class, decide on how you want the output. Print the TeX code to the screen? Use a subprocess to actually compile it to a pdf?
In my case, I was working on generating preliminary results for a research paper and needed to format tables into a complicated double-sorted structure with nested column names, etc. Here's an example of what one of the tables looks like:
Here is the mako template for this (warning, gross):
<%page args="df, table_title, group_var, sort_var"/>
<%
"""
Template for country/industry two-panel double sorts TeX table.
Inputs:
-------
df: pandas DataFrame
Must be 17 x 12 and have rows and columns that positionally
correspond to the entries of the table.
table_title: string
String used for the title of the table.
group_var: string
String naming the grouping variable for the horizontal sorts.
Should be 'Country' or 'Industry'.
sort_var: string (raw)
String naming the variable that is being sorted, e.g.
"beta" or "ivol". Note that if you want the symbol to
be rendered as a TeX symbol, then pass a raw Python
string as the arg and include the needed TeX markup in
the passed string. If the string isn't raw, some of the
TeX markup might be interpreted as special characters.
Returns:
--------
When used with mako.template.Template.render, will produce
a raw TeX string that can be rendered into a PDF containing
the specified data.
Author:
-------
Ely M. Spears, 05/21/2013
"""
# Python imports and helper function definitions.
import numpy as np
def format_helper(x):
return str(np.round(x,2))
%>
<%text>
\documentclass[10pt]{article}
\usepackage[top=1in, bottom=1in, left=1in, right=1in]{geometry}
\usepackage{array}
\newcolumntype{L}[1]{>{\raggedright\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}
\newcolumntype{C}[1]{>{\centering\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}
\setlength{\parskip}{1em}
\setlength{\parindent}{0in}
\renewcommand*\arraystretch{1.5}
\author{Ely Spears}
\begin{document}
\begin{table} \caption{</%text>${table_title}<%text>}
\begin{center}
\begin{tabular}{ | p{2.5cm} c c c c c p{1cm} c c c c c c p{1cm} |}
\hline
& \multicolumn{6}{c}{CAPM $\beta$} & \multicolumn{6}{c}{CAPM $\alpha$ (\%p.a.)} & \\
\cline{2-7} \cline{9-14}
& \multicolumn{6}{c}{</%text>${group_var}<%text> </%text>${sort_var}<%text> is:} & \multicolumn{6}{c}{</%text>${group_var}<%text> </%text>${sort_var}<%text> is:} & \\
Stock </%text>${sort_var}<%text> is: & Low & 2 & 3 & 4 & High & Low - High & & Low & 2 & 3 & 4 & High & Low - High \\
\hline
\multicolumn{4}{|l}{Panel A. Point estimates} & & & & & & & & & & \\
\hline
Low & </%text>${' & '.join(df.ix[0].map(format_helper).values[0:6])}<%text> & & </%text>${' & '.join(df.ix[0].map(format_helper).values[6:])}<%text> \\
2 & </%text>${' & '.join(df.ix[1].map(format_helper).values[0:6])}<%text> & & </%text>${' & '.join(df.ix[1].map(format_helper).values[6:])}<%text> \\
3 & </%text>${' & '.join(df.ix[2].map(format_helper).values[0:6])}<%text> & & </%text>${' & '.join(df.ix[2].map(format_helper).values[6:])}<%text> \\
4 & </%text>${' & '.join(df.ix[3].map(format_helper).values[0:6])}<%text> & & </%text>${' & '.join(df.ix[3].map(format_helper).values[6:])}<%text> \\
High & </%text>${' & '.join(df.ix[4].map(format_helper).values[0:6])}<%text> & & </%text>${' & '.join(df.ix[4].map(format_helper).values[6:])}<%text> \\
Low - High & </%text>${' & '.join(df.ix[5].map(format_helper).values[0:5])}<%text> & & & </%text>${' & '.join(df.ix[5].map(format_helper).values[6:11])}<%text> & \\
\multicolumn{6}{|l}{</%text>${group_var}<%text> effect (average of Low - High \underline{column})}
& </%text>${format_helper(df.ix[6,5])}<%text> & & & & & & & </%text>${format_helper(df.ix[6,11])}<%text> \\
\multicolumn{6}{|l}{Within-</%text>${group_var}<%text> effect (average of Low - High \underline{row})}
& </%text>${format_helper(df.ix[7,5])}<%text> & & & & & & & </%text>${format_helper(df.ix[7,11])}<%text> \\
\multicolumn{13}{|l}{Total effect} & </%text>${format_helper(df.ix[8,11])}<%text> \\
\hline
\multicolumn{4}{|l}{Panel B. t-statistics} & & & & & & & & & & \\
\hline
Low & </%text>${' & '.join(df.ix[9].map(format_helper).values[0:6])}<%text> & & </%text>${' & '.join(df.ix[9].map(format_helper).values[6:])}<%text> \\
2 & </%text>${' & '.join(df.ix[10].map(format_helper).values[0:6])}<%text> & & </%text>${' & '.join(df.ix[10].map(format_helper).values[6:])}<%text> \\
3 & </%text>${' & '.join(df.ix[11].map(format_helper).values[0:6])}<%text> & & </%text>${' & '.join(df.ix[11].map(format_helper).values[6:])}<%text> \\
4 & </%text>${' & '.join(df.ix[12].map(format_helper).values[0:6])}<%text> & & </%text>${' & '.join(df.ix[12].map(format_helper).values[6:])}<%text> \\
High & </%text>${' & '.join(df.ix[13].map(format_helper).values[0:6])}<%text> & & </%text>${' & '.join(df.ix[13].map(format_helper).values[6:])}<%text> \\
Low - High & </%text>${' & '.join(df.ix[14].map(format_helper).values[0:5])}<%text> & & & </%text>${' & '.join(df.ix[14].map(format_helper).values[6:11])}<%text> & \\
\multicolumn{6}{|l}{</%text>${group_var}<%text> effect (average of Low - High \underline{column})}
& </%text>${format_helper(df.ix[15,5])}<%text> & & & & & & & </%text>${format_helper(df.ix[15,11])}<%text> \\
\multicolumn{6}{|l}{Within-</%text>${group_var}<%text> effect (average of Low - High \underline{row})}
& </%text>${format_helper(df.ix[16,5])}<%text> & & & & & & & </%text>${format_helper(df.ix[16,11])}<%text> \\
\hline
\end{tabular}
\end{center}
\end{table}
\end{document}
</%text>
My wrapper to_tex.py looks like this (with example usage in the if __name__ == "__main__" section):
"""
to_tex.py
Class for handling strings of TeX code and producing the
rendered PDF via PDF LaTeX. Assumes ability to call PDFLaTeX
via the operating system.
"""
class to_tex(object):
"""
Publishes a TeX string to a PDF rendering with pdflatex.
"""
def __init__(self, tex_string, tex_file, display=False):
"""
Publish a string to a .tex file, which will be
rendered into a .pdf file via pdflatex.
"""
self.tex_string = tex_string
self.tex_file = tex_file
self.__to_tex_file()
self.__to_pdf_file(display)
print "Render status:", self.render_status
def __to_tex_file(self):
"""
Writes a tex string to a file.
"""
with open(self.tex_file, 'w') as t_file:
t_file.write(self.tex_string)
def __to_pdf_file(self, display=False):
"""
Compile a tex file to a pdf file with the
same file path and name.
"""
try:
import os
from subprocess import Popen
proc = Popen(["pdflatex", "-output-directory", os.path.dirname(self.tex_file), self.tex_file])
proc.communicate()
self.render_status = "success"
except Exception as e:
self.render_status = str(e)
# Launch a display of the pdf if requested.
if (self.render_status == "success") and display:
try:
proc = Popen(["evince", self.tex_file.replace(".tex", ".pdf")])
proc.communicate()
except:
pass
if __name__ == "__main__":
from mako.template import Template
template_file = "path/to/template.mako"
t = Template(filename=template_file)
tex_str = t.render(arg1="arg1", ...)
tex_wrapper = to_tex(tex_str, )
My choice was to directly pump the TeX string to pdflatex and leave as an option to display it.
A small snippet of code actually using this with a DataFrame is here:
# Assume calculation work is done prior to this ...
all_beta = pandas.concat([beta_df, beta_tstat_df], axis=0)
all_alpha = pandas.concat([alpha_df, alpha_tstat_df], axis=0)
all_df = pandas.concat([all_beta, all_alpha], axis=1)
# Render result in TeX
tex_mako = "/my_project/templates/mako/two_panel_double_sort_table.mako"
tex_file = "/my_project/some_tex_file_name.tex"
from mako.template import Template
t = Template(filename=tex_mako)
tex_str = t.render(all_df, table_title, group_var, tex_risk_name)
import my_project.to_tex as to_tex
tex_obj = to_tex.to_tex(tex_str, tex_file)
The simplest way available now is to display your dataframe as a markdown table. You may need to install tabulate for this.
In your code cell, when displaying dataframe, use following:
from IPython.display import Markdown, display
display(Markdown(df.to_markdown()))
Since it is a markdown table, nbconvert can easily translate this into latex.
How can I display LaTeX code in a IPython Notebook?
IPython notebook uses MathJax to render LaTeX inside html/markdown. Just put your LaTeX math inside $$.
$$c = \sqrt{a^2 + b^2}$$
Or you can display LaTeX / Math output from Python, as seen towards the end of the notebook tour:
from IPython.display import display, Math, Latex
display(Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx'))
This came up in a search I was just doing, found a better solution with some more searching, IPython notebooks now have a %%latex magic that makes the whole cell Latex without the $$ wrapper for each line.
Refer notebook tour for Rich Display System
LaTeX References:
Udacity's Blog has the Best LaTeX Primer I've seen: It clearly shows how to use LaTeX commands in easy to read, and easy to remember manner !! Highly recommended.
This Link has Excellent Examples showing both the code, and the rendered result !
You can use this site to quickly learn how to write LaTeX by example.
And, here is a quick Reference for LaTeX commands/symbols.
To Summarize: various ways to indicate LaTeX in Jupyter/IPython:
Examples for Markdown Cells:
inline, wrap in: $
The equation used depends on whether the the value of
$Vmax$ is R, G, or B.
block, wrap in: $$
$$H← 0 + \frac{30(G−B)}{Vmax−Vmin} , if Vmax = R$$
block, wrap in: \begin{equation} and \end{equation}
\begin{equation}
H← 60 + \frac{30(B−R)}{Vmax−Vmin} , if Vmax = G
\end{equation}
block, wrap in: \begin{align} and \end{align}
\begin{align}
H←120 + \frac{30(R−G)}{Vmax−Vmin} , if Vmax = B
\end{align}
Examples for Code Cells:
LaTex Cell: %%latex magic command turns the entire cell into a LaTeX Cell
%%latex
\begin{align}
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{align}
Math object to pass in a raw LaTeX string:
from IPython.display import Math
Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx')
Latex class. Note: you have to include the delimiters yourself. This allows you to use other LaTeX modes such as eqnarray:
from IPython.display import Latex
Latex(r"""\begin{eqnarray}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{eqnarray}""")
Docs for Raw Cells:
(sorry, no example here, just the docs)
Raw cells
Raw cells provide a place in which you can write output directly. Raw cells are not evaluated by the notebook. When passed through nbconvert, raw cells arrive in the destination format unmodified. For example, this allows you to type full LaTeX into a raw cell, which will only be rendered by LaTeX after conversion by nbconvert.
Additional Documentation:
For Markdown Cells, as quoted from Jupyter Notebook docs:
Within Markdown cells, you can also include mathematics in a straightforward way, using standard LaTeX notation: $...$ for inline mathematics and $$...$$ for displayed mathematics. When the Markdown cell is executed, the LaTeX portions are automatically rendered in the HTML output as equations with high quality typography. This is made possible by MathJax, which supports a large subset of LaTeX functionality
Standard mathematics environments defined by LaTeX and AMS-LaTeX (the amsmath package) also work, such as \begin{equation}...\end{equation}, and \begin{align}...\end{align}. New LaTeX macros may be defined using standard methods, such as \newcommand, by placing them anywhere between math delimiters in a Markdown cell. These definitions are then available throughout the rest of the IPython session.
Use $$ if you want your math to appear in a single line, e.g.,
$$a = b + c$$ (line break after the equation)
If you don't need a line break after the math, use single dollar sign $, e.g.,
$a = b + c$ (no line break after the equation)
You can choose a cell to be markdown, then write latex code which gets interpreted by mathjax, as one of the responders say above.
Alternatively, Latex section of the iPython notebook tutorial explains this well.
You can either do:
from IPython.display import Latex
Latex(r"""\begin{eqnarray}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{eqnarray}""")
or do this:
%%latex
\begin{align}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{align}
More info found in this link
I developed prettyPy, which offers a nice way to print equation. Unfortunately, it's not performant and needs testing.
Example:
Granted, sympy is a great alternative and although prettyPy doesn't allow for evaluating expressions, variable initialization is not required.
I wrote how to write LaTeX in Jupyter Notebook in this article.
You need to enclose them in dollar($) signs.
To align to the left use a single dollar($) sign.
$P(A)=\frac{n(A)}{n(U)}$
To align to the center use double dollar($$) signs.
$$P(A)=\frac{n(A)}{n(U)}$$
Use \limits for \lim, \sum and \int to add limits to the top and the bottom of each sign.
Use a backslash to escape LaTeX special words such as Math symbols, Latin words, text, etc.
Try this one.
$$\overline{x}=\frac{\sum \limits _{i=1} ^k f_i x_i}{n} \text{, where } n=\sum \limits _{i=1} ^k f_i $$
Matrices
Piecewise functions
$$
\begin{align}
\text{Probability density function:}\\
\begin{cases}
\frac{1}{b-a}&\text{for $x\in[a,b]$}\\
0&\text{otherwise}\\
\end{cases}
\\
\text{Cumulative distribution function:}\\
\begin{cases}
0&\text{for $x<a$}\\
\frac{x-a}{b-a}&\text{for $x\in[a,b)$}\\
1&\text{for $x\ge b$}\\
\end{cases}
\end{align}
$$
The above code will create this.
If you want to know how to add numbering to equations and align equations, please read this article for details.
Since, I was not able to use all the latex commands in Code even after using the %%latex keyword or the $..$ limiter, I installed the nbextensions through which I could use the latex commands in Markdown. After following the instructions here: https://github.com/ipython-contrib/IPython-notebook-extensions/blob/master/README.md and then restarting the Jupyter and then localhost:8888/nbextensions and then activating "Latex Environment for Jupyter", I could run many Latex commands. Examples are here: https://rawgit.com/jfbercher/latex_envs/master/doc/latex_env_doc.html
\section{First section}
\textbf{Hello}
$
\begin{equation}
c = \sqrt{a^2 + b^2}
\end{equation}
$
\begin{itemize}
\item First item
\item Second item
\end{itemize}
\textbf{World}
As you see, I am still unable to use usepackage. But maybe it will be improved in the future.
The answer given by minrk (included for completeness) is good, but there is another way that I like even more.
You can also render an entire cell as LaTeX by typing %%latex as the first line in a text cell. This is usefull if you
want more control,
want more than just a math environment,
or if you are going to write a lot of math in one cell.
minrk's answer:
IPython notebook uses MathJax to render
LaTeX inside html/markdown. Just put your LaTeX math inside $$.
$$c = \sqrt{a^2 + b^2}$$
Or you can display LaTeX / Math output from Python, as seen towards
the end of the notebook
tour:
from IPython.display import display, Math, Latex
display(Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx'))
If your main objective is doing math, SymPy provides an excellent approach to functional latex expressions that look great.
Using LaTeX syntax directly in a Markdown cell works for me. I'm using Jypiter 4.4.0.
I don't have to use %%latex magic command, I insist, simply a markdown cell:
\begin{align}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{align}
Renders to:
I came across this problem some day using colab. And I find the most painless way is just running this code before printing. Everything works like charm then.
from IPython.display import Math, HTML
def load_mathjax_in_cell_output():
display(HTML("<script src='https://www.gstatic.com/external_hosted/"
"mathjax/latest/MathJax.js?config=default'></script>"))
get_ipython().events.register('pre_run_cell', load_mathjax_in_cell_output)
import sympy as sp
sp.init_printing()
The result looks like this:
I am using Jupyter Notebooks.
I had to write
%%latex
$sin(x)/x$
to get a LaTex font.
Yet another solution for when you want to have control over the document preamble. Write a whole document, send it to system latex, convert the pdf to png, use IPython.display to load and display.
import tempfile
import os.path
import subprocess
from IPython.display import Image, display
with tempfile.TemporaryDirectory(prefix="texinpy_") as tmpdir:
path = os.path.join(tmpdir, "document.tex")
with open(path, 'w') as fp:
fp.write(r"""
\documentclass[12pt]{standalone}
\begin{document}
\LaTeX{}
\end{document}
""")
subprocess.run(["lualatex", path], cwd=tmpdir)
subprocess.run(["pdftocairo", "-singlefile", "-transp", "-r", "100", "-png", "document.pdf", "document"], cwd=tmpdir)
im = Image(filename=os.path.join(tmpdir, "document.png"))
display(im)
If you want to display a LaTeX equation from a notebook code cell you can create a simple wrapper class that makes use of the Jupyter notebooks rich display representation. This class should have a _repr_latex_ method (note this single underscore at the start and end rather than the double underscores of other special methods) that outputs the LaTeX string. E.g.:
class LaTeXEquation:
def __init__(self, eqntext):
self.eqntext = eqntext
def __repr__(self):
return repr(self.eqntext)
def _repr_latex_(self):
"""
Special method for rich display of LaTeX formula.
"""
# add $'s at start and end if not present
if self.eqntext.strip()[0] != "$" and self.eqntext.strip()[-1] != "$":
return "$" + self.eqntext + "$"
else:
return self.eqntext
myeqn = "x = y^2"
Then in a code cell, if you do, e.g.,
LaTeXEquation(myeqn)
it will show the formatted equation.
I'm completely new to LaTeX and have the MacTeX 2009 package installed, with the intent of having tables from R output into LaTeX and formatted as PDF.
I get the following LaTeX code (below) when I run an example in R (it renders ok in R, but I´d like to use TeXshop). However, when I paste this into a TeXshop window, I get the following error:
./Untitled.tex:2: LaTeX Error: Environment table undefined
I´m sure there is something very basic I´m missing here.
% latex.default(cstats, title = title, caption = caption, rowlabel = rowlabel,
% col.just = col.just, numeric.dollar = FALSE, insert.bottom = legend,
% rowname = lab, dcolumn = dcolumn, extracolheads = extracolheads,
% extracolsize = Nsize, ...)
%
\begin{table}[!tbp]
\caption{Descriptive Statistics by treatment\label{f}}
\begin{center}
\begin{tabular}{lccc}\hline\hline
\multicolumn{1}{l}{}&\multicolumn{1}{c}{Drug}&\multicolumn{1}{c}{Placebo}&\multicolumn{1}{c}{Test Statistic}\tabularnewline
&\multicolumn{1}{c}{{\scriptsize $N=263$}}&\multicolumn{1}{c}{{\scriptsize $N=237$}}&\tabularnewline
\hline
age&{\scriptsize 46.5~}{49.9 }{\scriptsize 53.2} &{\scriptsize 46.7~}{50.0 }{\scriptsize 53.4} &$ F_{1,498}=0.1 ,~ P=0.754 ^{1} $\tabularnewline
sex~:~m&47\%~{\scriptsize~(123)}&44\%~{\scriptsize~(104)}&$ \chi^{2}_{1}=0.42 ,~ P=0.517 ^{2} $\tabularnewline
Primary~Symptoms~:~Depressed&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$\tabularnewline
~~~~Headache&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$\tabularnewline
~~~~Hangnail&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$\tabularnewline
~~~~Muscle~Ache&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$\tabularnewline
~~~~Stomach~Ache&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$\tabularnewline
\hline
\end{tabular}
\end{center}
\noindent
{\scriptsize $a$\ }{$b$\ }{\scriptsize $c$\ } represent the lower quartile $a$,
the median $b$, and the upper quartile $c$\ for continuous variables.\\
Numbers after percents are frequencies.\\\indent Tests used:\\
\textsuperscript{\normalfont 1}Wilcoxon test; \textsuperscript{\normalfont 2}Pearson test
\end{table}
You need some boilerplate around this to set up the document -- the LaTeXTemplate in TexShop should do.
Your \begin{table} is commented out with a preceding %
There are some missing backslashes in the legend text -- possibly these are just cut & paste artefacts?
This thrown-together version works for me, though you may need to tweak it for your purposes:
\documentclass[11pt]{article}
\begin{document}
\begin{table}[!tbp]
\caption{Descriptive Statistics by treatment\label{f}}
\begin{center}
\begin{tabular}{lccc}
\hline
\hline
\multicolumn{1}{l}{}&\multicolumn{1}{c}{Drug}&\multicolumn{1}{c}{Placebo}&\multicolumn{1}{c}{Test Statistic}
\tabularnewline
&\multicolumn{1}{c}{{\scriptsize $N=263$}}&\multicolumn{1}{c}{{\scriptsize $N=237$}}&
\tabularnewline
\hline
age&{\scriptsize 46.5~}{49.9 }{\scriptsize 53.2} &{\scriptsize 46.7~}{50.0 }{\scriptsize 53.4} &$ F_{1,498}=0.1 ,~ P=0.754 ^{1}$
\tabularnewline
sex~:~m&47\%~{\scriptsize~(123)}&44\%~{\scriptsize~(104)}&$ \chi^{2}_{1}=0.42 ,~ P=0.517 ^{2} $
\tabularnewline
Primary~Symptoms~:~Depressed&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$
\tabularnewline
~~~~Headache&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$
\tabularnewline
~~~~Hangnail&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$
\tabularnewline
~~~~Muscle~Ache&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$
\tabularnewline
~~~~Stomach~Ache&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$
\tabularnewline
\hline
\end{tabular}
\end{center}
\noindent {\scriptsize $a$\ }{$b$\ }{\scriptsize $c$\ } represent the lower quartile $a$, the median $b$, and the upper quartile $c$ for continuous variables.\\
Numbers after percents are frequencies.\\
\indent Tests used:\\
\textsuperscript{\normalfont 1}Wilcoxon test;
\textsuperscript{\normalfont 2}Pearson test
\end{table}
\end{document}
If you use the package stargazer (available on CRAN), you can use the argument out="filename.tex" to output the LaTeX code directly into a Tex document. That document should then be easy to compile.
It sounds like you may not have a document class defined, or you are not using a document class that defines the table environment.
I'm trying to learn LaTeX, currently because otherwise, my professors will be nearly unable to read my homework assignments. I've come across something I want to do, but don't seem to be able to, ie. I have searched google (possibly with a poor keyword set) and not found a solution.
The specific case is as follows: I want to put an ams flalign environment inside a box and have multiple such environments side by side. I have achieved this using minipage, but minipage asks for a width. I would like to use the smallest width in which the flalign environment fits. I realize that I can set the width to 0pt, but I can't help wondering if there's something that is intended to do this.
Also, should I be using minipage? Is there another command I don't know?
Thanks for your reply.
EDIT:
An attempted clarification as to what I want to do. I want equations which are standard, known, given, etc. and short on the left. To the right of those, I want relevant derived equations (and maybe their derivations. Further right, I want actual calculations plugged in.
I feel like what I want is a tabular environment with 3 columns, but I don't think I can put an equation environment in a tabular environment.
This looks like what I want when I render it.
\begin{minipage}[t]{0pt}
\begin{flalign*}
\sigma & = F / A&\\
A & = \pi \left(d/2\right)^2&\\
\epsilon &= \frac{\sigma}{E}&\\
\epsilon_{trans} &= - \nu \epsilon_{longi}& \\
\epsilon &= \frac{\Delta l}{l}&\\
l &= \left( \epsilon + 1 \right) \times l_0&
\end{flalign*}
\end{minipage}
\hspace*{0pt}
\begin{minipage}[t]{0pt}
\begin{flalign*}
d & = \unit[1.8]{mm} = \unit[1.8\e{-3}]{m} &\\
F_T & = \unit[1300]{N}&\\
E_{\text{stainless steel}}&=\unit[193\e9]{Pa}&\\
l_0 & = \unit[.2530]{m}&\\
\nu & = .33&\\
\sigma &= \frac{\unit[1300]{N}}{\pi \times \unit[3.24\e{-6}]{m^2}}&&= \boxed{\unit[127.7\e6]{Pa}}\\
&&&=\boxed{\unit[18,524]{psi}}\\
\epsilon &= \frac{\unit[127.7\e6]{Pa}}{\unit[193\e9]{Pa}} &&= \boxed{6.6\e{-2}}\\
\epsilon_{trans} &= -.33 \times 6.6\e{-2} &&=\boxed{-2.2\e{-2}}\\
l &= \left( 6.6\e{-2} + 1 \right) \times \unit[.2530]{m} &&= \boxed{\unit[.2797]{m}}
\end{flalign*}
\end{minipage}
I'm not sure exactly what you're trying to achieve, but amsmath's align* environment might do what you want (without resorting to minipages):
\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{align*}
x&=y & X&=Y & a&=b+c & mn&=ab\\
x’&=y’ & X’&=Y’ & a’&=b & m'n'&=a'b'\\
x+x’&=y+y’ & X+X’&=Y+Y’ & a’b&=c’b & m'&=a'
\end{align*}
\end{document}
As to your minipage question: it requires a width because TeX needs to know where to break the lines. If you don't want the line-breaking algorithm to be used, you probably don't want a minipage.
Edit:
If you want multiple columns and don't care about the vertical alignment of material across the columns, that can be obtained easily enough with the multicols package:
\documentclass{article}
\usepackage{multicols}
\usepackage{lipsum}% just for some example text
\begin{document}
% The * version allows the columns to have ragged bottoms.
% The argument 2 is the number of columns.
\begin{multicols*}{2}
\lipsum[1]% one paragraph of Lorem ipsum.. filler text
\vfil% fills the remainder of the column with white space
\columnbreak% force a column break
\lipsum[2]% another paragraph of text
\vfil% fills the remainder of the column with white space
\end{multicols*}
\end{document}
You might find something to help you in the empheq and mathtools packages. empheq allows you to box equations and mathtools should provide some useful environments for stacking them horizontally.