Skip to content

Commit

Permalink
First commit: tables and figures
Browse files Browse the repository at this point in the history
  • Loading branch information
sergiocorreia committed Apr 25, 2016
1 parent 3b47358 commit f12ff04
Show file tree
Hide file tree
Showing 7 changed files with 526 additions and 0 deletions.
141 changes: 141 additions & 0 deletions example/advanced.md
@@ -0,0 +1,141 @@
---
title: Some Title
author: Lorem Ipsum
date: Some Date
graphics: True
mainfont: 'Minion Pro'
format:
backmatter: True
show-frame: False
header-includes:
- \usepackage{setspace}
- \doublespacing
- \usepackage{ragged2e} # Allows \justify in figure footnotes
cmd:
tex: 'cls & pandoc advanced.md --latex-engine=xelatex --filter=pandoc-figure --output=output.pdf && output.pdf'
html: 'cls & pandoc advanced.md --filter=pandoc-figure --output=output.html && output.html'
---

# Advanced filters with panflute

First we will add a figure:

~~~ figure
title: Mapping *Migration* _Flows_ ~in~ 1862
source: 'minard.png'
label: 'migration'
innerwidth: 0.8
...
Write notes and sources here. Feel *free* to write a lot, use **markdown**, etc.
Charles Joseph Minard’s World Map/Sankey Diagram of Migration 1862; [CC-BY-SA Attribution](http://www.martingrandjean.ch/historical-data-visualization-mapping-migration-in-1862/).
UTF should also work: пустынных волн. Τη γλώσσα μου έδωσαν ελληνική. Done!
~~~


We can also add it with a fancier format:

```
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ figure
title: Mapping *Migration* _Flows_ ~in~ 1862
source: 'minard.png'
label: 'migration'
innerwidth: 0.8
...............................................................................
Write notes and sources here. Feel *free* to write a lot, use **markdown**, etc.
Charles Joseph Minard’s World Map/Sankey Diagram of Migration 1862; [CC-BY-SA Attribution](http://www.martingrandjean.ch/historical-data-visualization-mapping-migration-in-1862/).
UTF should also work: пустынных волн. Τη γλώσσα μου έδωσαν ελληνική. Done!
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
```


This is how it looks normally (i.e. with no captions):

![ Mapping *Migration* _Flows_ ~in~ 1862](minard.png "Mapping Migration Flows in 1862")

## Tables

Now a table:


~~~ table
title: Retail Stores by Chain (August 2012)
label: summary-stores
source: 'stores.tex'
...
This table reports the number of retail stores existing as of August 2012, by store chain and region. Lima refers to *Lima Metropolitan Area*, formed by the conurbation of Lima (Peru''s capital) and Callao. The *2006--* columns refer both to store openings between Jan2006--Aug2012 and to existing stores as of Aug2012, since there were no stores closings in that period. As in the rest of the paper, the *Lima Cercado* district, with nine store openings, has been excluded. The full listing of stores is [available online](http://scorreia.com/research/credit-cards/).
~~~




And another


~~~ table
alignment: LCR
caption: This is the **caption** # Markdown in caption requires pypandoc
header: true
source: table-advanced.csv
~~~


~~~ table
alignment: LCR
caption: This is the **caption**
header: true
---
Fruit, Quantity, Price
apples, 15, 3.24
oranges, 12, 2.22
~~~



~~~ table
title: Credit Cards by Bank (August 2012)
notes: 'This table reports the number of credit cards (in thousands) and volume of credit card lending (in US dollars) per bank in August 2012, as well as the name of the retail chains belonging to the same conglomerate. *Other banks* comprise Banco Azteca, HSBC Bank, BIF, Mibanco and Banco de Comercio, each with less than \(1\%\) market share in terms of both cards and volume. Source: Superintendencia de Banca, Seguros y AFP.'
label: summary-banks
source: 'table-advanced.tex'
~~~

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.


~~~ algorithms
title: K-Means
input: $\vx, \vy$
output: $\vz \in \SR$
steps:
1. Something
2. Something else
~~~

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

~~~ stata
title: A Stata Table
source: '../tmp/stuff.csv'
refresh: false
---
sysuse auto
collapse (mean) price, by(foreign)
outsheet using '../tmp/stuff.csv', replace
exit, STATA // implicit?
~~~


$backmatter
1 change: 1 addition & 0 deletions example/cmd.txt
@@ -0,0 +1 @@
cls & pandoc --latex-engine=xelatex --filter=pandoc-figure --standalone -o output.pdf advanced.md && output.pdf
Binary file added example/minard.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
48 changes: 48 additions & 0 deletions example/stores.tex
@@ -0,0 +1,48 @@
{
\begin{table}[htb]
\captionsetup{singlelinecheck=on,labelfont=bf,labelsep=colon,font=bf,justification=centering}
\setmainfont[Numbers={Proportional, OldStyle}]{Minion Pro}%
\setmainfont[Numbers={Monospaced, Lining}]{Minion Pro}%
\sisetup{%
input-symbols=(),%
group-digits=integer,% true false integer decimal
table-format = 2.0,
table-column-width=0.8cm
%color=red
}

\setlength{\tabcolsep}{0.1cm}
\caption{$title}\label{table:$label}
\centering
\begin{threeparttable}
\renewcommand{\TPTminimum}{0cm} % Need to reset it to zero otherwise it will be left aligned
\begin{tabular}{ *{4}{l} *{6}{r} }
\toprule
{Company} & {Sister Bank} & {Chain} & {Store Type} &
\multicolumn{2}{c}{Peru} & \multicolumn{2}{c}{Lima} & \multicolumn{2}{c}{Other Cities} \\ \cmidrule(lr){5-6} \cmidrule(lr){7-8} \cmidrule(lr){9-10}
& & & & \multicolumn{1}{c}{Total} & \multicolumn{1}{c}{2006--} & \multicolumn{1}{c}{Total} & \multicolumn{1}{c}{2006--} & \multicolumn{1}{c}{Total} & \multicolumn{1}{c}{2006--} \\
\midrule
Falabella & Falabella & Tottus & Hypermarket & 28 & 25 & 18 & 15 & 10 & 10 \\
& & Saga & Dept. Store & 23 & 14 & 9 & 5 & 14 & 9 \\
& & Sodimac & Warehouse & 17 & 15 & 8 & 6 & 9 & 9 \\
\\
SPSA & Interbank & Plaza Vea & Hypermarket & 52 & 38 & 35 & 21 & 17 & 17 \\
& & Vivanda & Supermarket & 8 & 3 & 8 & 3 & 0 & 0 \\
& & Oechsle & Dept. Store & 6 & 6 & 2 & 2 & 4 & 4 \\
\\
Cencosud & --- & Super Metro & Supermarket & 31 & 30 & 24 & 23 & 7 & 7 \\
& & Hiper Metro & Hypermarket & 14 & 2 & 14 & 2 & 0 & 0 \\
& & Wong & Supermarket & 13 & 3 & 12 & 2 & 1 & 1 \\
\\
Ripley & Ripley & Ripley & Dept. Store & 17 & 10 & 12 & 5 & 5 & 5 \\
\\
Makro & --- & Makro & Warehouse & 8 & 8 & 5 & 5 & 3 & 3 \\
\midrule\multicolumn{4}{l}{Total} & 217 & 154 & 147 & 89 & 70 & 65 \\
\bottomrule
\end{tabular}
\begin{tablenotes}\small
\Note{$notes}
\end{tablenotes}
\end{threeparttable}
\end{table}
}
108 changes: 108 additions & 0 deletions panflutefilters/figure.py
@@ -0,0 +1,108 @@
#!/usr/bin/env python

# ---------------------------
# Imports
# ---------------------------

import os
from string import Template

import panflute as pf


# ---------------------------
# Constants
# ---------------------------

LATEX_TEMPLATE = Template(r"""
%%%% BEGIN FIGURE %%%%
$pagebreak
{\setstretch{1.0} % Force single spacing for media
\begin{figure}[htbp]
\centering
\begin{minipage}[c]{$width\textwidth}
\vspace{10pt}
\centering\includegraphics[width=$innerwidth\linewidth]{"$fn"} \\
\caption{$title}\label{fig:$label}
\medskip
\justify
\$notesize
$notes
\end{minipage}
\end{figure}
\par
} % End single spacing
%%%% END FIGURE %%%%
""")


# ---------------------------
# Functions
# ---------------------------

def prepare(doc):
doc.backmatter = []


def finalize(doc):
if doc.backmatter:
doc.replacement_ok = False
backmatter = pf.Div(*doc.backmatter, identifier='backmatter')
pf.replace_keyword(doc, '$backmatter', backmatter)
assert doc.replacement_ok, "Couldn't replace '$backmatter'"
else:
pf.replace_keyword(doc, '$backmatter', pf.Null())

def figure(options, data, element, doc):

# Get options
fn = os.path.abspath(options['source']).replace('\\', '/')
title = options.get('title', 'Untitled')
notes = data
label = options.get('label', os.path.splitext(os.path.basename(fn))[0])

if doc.format == 'latex':
subs = {'fn': fn, 'label': label}
subs['title'] = pf.convert_markdown(title, format='latex')
subs['notes'] = pf.convert_markdown(notes, format='latex')
backmatter = doc.get_metadata('format.backmatter', False)
pagebreak = doc.get_metadata('format.media-pagebreak', False)

w = options.get('width', 1.0)
subs['width'] = w
subs['innerwidth'] = options.get('innerwidth', w) / w
subs['notesize'] = options.get('notesize', 'small')
subs['pagebreak'] = '\\clearpage\n' if pagebreak else ''

text = LATEX_TEMPLATE.safe_substitute(subs)
ans = pf.RawBlock(text=text, format='latex')

if backmatter:
doc.backmatter.append(ans)
msg = '\hyperref[fig:{}]{{[\Cref{{fig:{}}} Goes Here]}}'
msg = msg.format(label, label)
return pf.Plain(pf.Str(msg))
else:
return ans
else:
title = pf.convert_markdown(title)
assert len(title)==1, title
title = (title[0]).items

notes = pf.Div(*pf.convert_markdown(notes), classes=['note'])
title_text = pf.stringify(title)
img = pf.Image(*title, url=fn, title=title_text, identifier=label)
ans = pf.Div(pf.Plain(img), pf.Plain(pf.LineBreak), notes, classes=['figure'])
return ans

def main():
pf.toJSONFilter(pf.yaml_filter, prepare=prepare, finalize=finalize,
tag='figure', function=figure)


# ---------------------------
# Main
# ---------------------------

if __name__ == "__main__":
main()

0 comments on commit f12ff04

Please sign in to comment.