Skip to content

Instantly share code, notes, and snippets.

@yblein
Last active January 25, 2016 10:44
Show Gist options
  • Save yblein/6d586633667cd2518c70 to your computer and use it in GitHub Desktop.
Save yblein/6d586633667cd2518c70 to your computer and use it in GitHub Desktop.
Print a tex file plotting the given csv file with pgfplots
#!/usr/bin/python
# Print a tex file plotting the given csv file with pgfplots
import csv
import sys
if len(sys.argv) < 2:
print "error: expected csv filename"
sys.exit()
filename = sys.argv[1]
with open(filename) as f:
# guess the dialect of the CSV file
dialect = csv.Sniffer().sniff(f.read(1024))
f.seek(0)
# read csv header
r = csv.reader(f, dialect)
header = r.next()
print """\\documentclass[tikz,border=1pt]{standalone}
\\usepackage[T1]{fontenc}
\\usepackage[utf8]{inputenc}
\\usepackage{pgfplots}
\\begin{document}
\\begin{tikzpicture}
\\pgfplotstableread[col sep = comma]{%s}\data
\\begin{axis}[xlabel=\\detokenize{%s}, ylabel=\\detokenize{%s}, table/x index={0}]""" % (filename, header[0], "")
for i in range(1, len(header)):
print "\\addplot table [y index={%d}] {\data};" % (i)
print "\\addlegendentry{\\detokenize{%s}}" % header[i]
print """\\end{axis}
\\end{tikzpicture}
\\end{document}"""
@yblein
Copy link
Author

yblein commented Jan 25, 2016

Example

Input CSV file content

x,x^2,x^3
0,0,0
1,1,1
2,4,8
3,9,27
4,16,64

Result

doc

@yblein
Copy link
Author

yblein commented Jan 25, 2016

This can probably be coded directly in LaTeX, without resorting to an external script.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment