Skip to content

Instantly share code, notes, and snippets.

@yzh119
Created August 1, 2022 00:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yzh119/2c97be931d50c9adba41cce166c9d5d8 to your computer and use it in GitHub Desktop.
Save yzh119/2c97be931d50c9adba41cce166c9d5d8 to your computer and use it in GitHub Desktop.
A python wrapper of gnuplot
import subprocess
from typing import List, Tuple, Callable
plt_header = """
set output "{}.ps"
"""
def plot(
filename: str,
prelude: str,
subplots: List[Tuple[str, str]],
label_str: str,
label_x_offset_func: Callable,
p_list: List,
ls_list: List,
):
with open(filename + ".plt", "w") as f_out:
f_out.write(plt_header.format(filename) + "\n")
f_out.write(prelude + "\n")
for subplot in subplots:
name, text = subplot
f_out.write(text + "\n")
with open(name + ".dat", "r") as f_in:
lines = f_in.readlines()
num_rows = len(lines)
num_cols = len(lines[0].split())
for i in range(num_cols - 1):
fmt_str = "fs {} fc ls {} lw 3 ti col".format(p_list[i], ls_list[i])
if i == 0:
f_out.write(
"""plot "{}" u (y_val($2)):xtic(1) {},\\\n""".format(
name + ".dat", fmt_str
)
)
else:
f_out.write("""'' u (y_val(${})) {},\\\n""".format(i + 2, fmt_str))
f_out.write(
"""'' u ($0+({})):(y_pos(${})):(to_str(${})) {}""".format(
label_x_offset_func(i), i + 2, i + 2, label_str
)
)
if i != num_cols - 2:
f_out.write(",\\\n")
else:
f_out.write("\n")
subprocess.call(["gnuplot", filename + ".plt"])
subprocess.call(["epstopdf", filename + ".ps"])
subprocess.call(["rm", filename + ".plt"])
subprocess.call(["rm", filename + ".ps"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment