Giter Club home page Giter Club logo

labella.py's Introduction

labella.py

image

image

image

Labella.py is a Python 3 clone of labella.js that supports all the features of labella.js and addionally can generate TikZ PDF images for use in LaTeX.

Note: This package is for the most part a direct translation of the original labella.js code to Python 3. All the credit for the labella code goes to Krist Wongsuphasawat (@kristw), I only added the code that generates PDF output. Labella.py also includes code from d3 for axis scaling, and WebCola for the VPSC code (label placement optimization).

Why?

I wrote this for multiple reasons, the most important of which is that I wanted to incorporate label graphs like the ones generated by labella.js in PDF documents, but wasn't satisfied with the PDF output generated by SVG-to-PDF converters. Additionally, it seemed like a fun way to learn some more Javascript, and learn about how labella.js works.

Screenshots

These screenshots show the PDF output generated by labella.py (converted to .png)

Time scale:

Example of Labella.py output for a timeline

Linear scale:

Example of Labella.py output for a timeline

Usage

Using labella.py is extremely similar to using labella.js. See the examples directory for examples of how to use labella.py. These examples are translations of the examples included in labella.js and in d3kit-timeline.

For ease of use only the Timeline interface is implemented, which works similar to d3kit-timeline. Here is a minimal working example for exporting to PDF:

>>> from labella.scale import LinearScale
>>> from labella.timeline import TimelineTex
>>> tl = TimelineTex([
  {'time': 1, 'text': 'Minimal'},
  {'time': 2, 'text': 'Working'},
  {'time': 3, 'text': 'Example'}
  ], options={'scale': LinearScale()})
>>> tl.export('minimal.tex')

See also the documentation here.

Installation

Labella.py is available through PyPi, so you can do:

pip install labella

to install it.

Note: Labella.py requires a working LaTeX distribution for both SVG and PDF output (see also the documentation), and has only been tested on Linux. If you run into problems, please open an issue on GitHub.

Author

Gertjan van den Burg (@GjjvdBurg).

Licensed under the Apache License Version 2.0.

labella.py's People

Contributors

ashthespy avatar gjjvdburg avatar sdvillal avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

labella.py's Issues

How to adjust node size and font size?

Hello,

I'm having trouble adjusting labella/nodeHeight and latex/fontsize options.

Example:

  • If I set nodeHeight to say, 80, nothing happens to the resulting .pdf or .svg
  • If I set fontSize to say, 18, nothing happens to the resulting .pdf or .svg either

Options:

options = {
        "margin": {"left": 70, "right": 20, "top": 20, "bottom": 20},
        "initialWidth": 1300,
        "initialHeight": 1600,
        "direction": "right",
        "dotColor": "#000000",
        "labelBgColor": "#000000",
        "linkColor": "#000000",
        "textFn": lambda x: str(x["time"].date()) + " - " + x["text"],
        "labelPadding": {"left": 2, "right": 0, "top": 2, "bottom": 0},
        "labella": {
            "nodeHeight": 30,
        },
        "latex": {"fontsize": "15pt", "reproducible": True},
    }

Do you have any ideas for how to control these options?

Width caluculation - switch to TikZ?

Just found this package - must say it makes life easier!

For the LaTeX output, are the precompuation of the widths really required?
i.e couldn't

\begin{scope}[shift={(40, 3)}]
\fill[color=labelBgColorA, rounded corners=2pt]
(0, 0) rectangle (489, 16.65201) node[midway, yshift=-.75bp, anchor=center, 
           text=labelTextColorA] {\strut \textA};
\end{scope}

be simplified to:

\begin{scope}[shift={(40, 3)}]
\node[rectangle,text centered,anchor=north west,
           rounded corners=2pt,fill=labelBgColorA,yshift=-.75bp] at (0,0) {\strut \textA};
\end{scope}

This would let TikZ figure out the width of the label, rather than having to compute it

Horizontal Timeline up and down

Dear @GjjvdBurg,

Thank you for your work. I see your timeline and do you have a horizontal timeline with up and down features. I mean that we can write on both sides. At this moment, I checked your examples files in which we can only write on up or down sides.

Regards,
Khawar

FileNotFoundError: [WinError 2] The system cannot find the file specified

Hello,

I'm new to Python. Really excited to use your module, but I seem to be stuck.. Hoping you can help.

Error:

FileNotFoundError: [WinError 2] The system cannot find the file specified

Steps to reproduce:

  1. Create a Python virtual env in a new folder: python -m venv .venv
  2. Activate venv: .\.venv\Scripts\activate
  3. pip install labella, success
  4. Copy your example timeline_kit_1.py, paste in a new file in folder timeline.py
  5. Execute example: python .\timeline.py

Results in the above error.

Preliminary search:

  • Indicates that a filename could be incorrect(?)
  • It seems that the tl = TimelineSVG(items, options=options) line causes the problem. If I comment it out, the script executes (though of course, no output).

Error Full-text:

(.venv) PS E:\dataDocuments\python\timeline_test> python .\timeline.py
Traceback (most recent call last):
  File "E:\dataDocuments\python\timeline_test\timeline.py", line 64, in <module>
    main()
  File "E:\dataDocuments\python\timeline_test\timeline.py", line 56, in main
    tl = TimelineSVG(items, options=options)
  File "E:\dataDocuments\python\timeline_test\.venv\lib\site-packages\labella\timeline.py", line 311, in __init__
    super().__init__(items, options=options, output_mode="svg")
  File "E:\dataDocuments\python\timeline_test\.venv\lib\site-packages\labella\timeline.py", line 145, in __init__
    self.items = self.parse_items(dicts, output_mode=output_mode)
  File "E:\dataDocuments\python\timeline_test\.venv\lib\site-packages\labella\timeline.py", line 179, in parse_items
    it = Item(
  File "E:\dataDocuments\python\timeline_test\.venv\lib\site-packages\labella\timeline.py", line 97, in __init__
    self.width, self.height = self.get_text_dimensions()
  File "E:\dataDocuments\python\timeline_test\.venv\lib\site-packages\labella\timeline.py", line 103, in get_text_dimensions
    width, height = text_dimensions(self.text, fontsize="12pt")
  File "E:\dataDocuments\python\timeline_test\.venv\lib\site-packages\labella\tex.py", line 139, in text_dimensions
    width, height = get_latex_dims(tex, silent=silent,
  File "E:\dataDocuments\python\timeline_test\.venv\lib\site-packages\labella\tex.py", line 106, in get_latex_dims
    compile_latex(fname, tmpdirname, latexmk_options, silent=silent)
  File "E:\dataDocuments\python\timeline_test\.venv\lib\site-packages\labella\tex.py", line 91, in compile_latex
    raise (e)
  **File "E:**\dataDocuments\python\timeline_test\.venv\lib\site-packages\labella\tex.py", line 89, in compile_latex
    output = subprocess.check_output(command, stderr=subprocess.STDOUT)
  **File "C:**\Python39\lib\subprocess.py", line 424, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  File "C:\Python39\lib\subprocess.py", line 505, in run
    with Popen(*popenargs, **kwargs) as process:
  File "C:\Python39\lib\subprocess.py", line 951, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Python39\lib\subprocess.py", line 1420, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified
  • I don't know why my interpreter shifts from E: to C:, Thats weird

How to use URL hyperlinks for timeline events?

Hello!

Starting to get acquainted with the tool. Its nice! Thank you.

  • Where should I add hyperlinks for timeline events?
    • I tried adding them to the items array, like this, but no-go:
items = [
    {
         "time": date(1986, 1, 1), 
         "text": "\\href{http://www.overleaf.com}{Something Linky}"
     },
     {
         "time": date(1991, 1, 1),
         "text": "\\href{http://www.overleaf.com}{Something Linky}",
    }
]
  • Also tried adding it under options to the textfn lambda. But that didn't work.
  • Ideally I need the href to be usable in the PDF output
  • Please give an example using timeline_kit_1.py if possible.

borderColor not working

Using the following borderColor setting inside the options doct did not have any visible effect:

"labelBgColor":  "#fff",
"borderColor": "#000",
"labelTextColor": "#000",

This displayed black text on white background without any border for me. Is that expected?

Latexmk issue within Conda Env

Dear all,

I just tried to run the examples from https://github.com/GjjvdBurg/labella.py/blob/master/examples/timeline_kit_1.py
I installed within conda enviorement the latexmk, I tested with:

from labella.tex import text_dimensions
text_dimensions("foo", silent=False)
#___output___#


Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Director\anaconda3\envs\allinone\lib\site-packages\labella\tex.py", line 140, in text_dimensions
    latexmk_options=latexmk_options)
  File "C:\Users\Director\anaconda3\envs\allinone\lib\site-packages\labella\tex.py", line 106, in get_latex_dims
    compile_latex(fname, tmpdirname, latexmk_options, silent=silent)
  File "C:\Users\Director\anaconda3\envs\allinone\lib\site-packages\labella\tex.py", line 91, in compile_latex
    raise (e)
  File "C:\Users\Director\anaconda3\envs\allinone\lib\site-packages\labella\tex.py", line 89, in compile_latex
    output = subprocess.check_output(command, stderr=subprocess.STDOUT)
  File "C:\Users\Director\anaconda3\envs\allinone\lib\subprocess.py", line 411, in check_output
    **kwargs).stdout
  File "C:\Users\Director\anaconda3\envs\allinone\lib\subprocess.py", line 488, in run
    with Popen(*popenargs, **kwargs) as process:
  File "C:\Users\Director\anaconda3\envs\allinone\lib\subprocess.py", line 800, in __init__
    restore_signals, start_new_session)
  File "C:\Users\Director\anaconda3\envs\allinone\lib\subprocess.py", line 1207, in _execute_child
    startupinfo)
[WinError 2] The system cannot find the file specified

This is the same error as [(https://github.com//issues/14)]

Does anyone have the same issue?
Stay safe and best regards,
Tonino

I think I'm missing something in my machine to run it but I don't know what.

Hello, great library. Thanks for developing it!

I'm trying to get a timeline and in VSC and Jupyter Lab I get the "[WinError 2] The system cannot find the file specified", I used pip install and the library loads just fine with example code, it just won't output anything because of that error. What do I need to have installed to run this? specially the tl = TimelineTex(items, options=options) line.

Must be a noob question, but I thought I'd ask. Thanks again!

How to convert timeline to .png?

Hello,

I'm trying to convert the .svg generated by one of the examples to .png.

Tried appending THIS CODE to the main() function below:

#Reference: https://stackoverflow.com/a/70357769/5976033
#!pip install cairosvg

import os
import cairosvg
from datetime import date
from labella.timeline import TimelineSVG, TimelineTex


def main():
    items = [
        {
            "time": date(1986, 1, 1), 
            "text": "Willy Wonka"
        },
        {
            "time": date(1991, 1, 1),
            "text": "Goonies",
        },
        {
            "time": date(2021, 4, 1),
            "text": "Matrix",
        }
    ]

    options = {
        "margin": {"left": 40.5, "right": 20, "top": 20, "bottom": 20},
        "initialWidth": 1600,
        "initialHeight": 1600,
        "direction": "right",
        "dotColor": "#000000",
        "labelBgColor": "#000000",
        "linkColor": "#000000",
        "textFn": lambda x: "{\\fontfamily{phv}\\selectfont" + str(x["time"].date()) + " - " + x["text"] + "}",
        "labelPadding": {"left": 2, "right": 0, "top": 0, "bottom": 0},
        "labella": {
            "nodeHeight": 22,
        },
        "latex": {"fontsize": "12pt", "reproducible": True},
    }

    tl = TimelineSVG(items, options=options)
    tl.export("timeline_kit_1.svg")

    tl = TimelineTex(items, options=options)
    tl.export("timeline_kit_1.tex")

#------------THIS CODE---------------------------
    cairosvg.svg2png(
    url="timeline_kit_1.svg", write_to="timeline_kit_1.png")

#----------------------------------------------------
if __name__ == "__main__":
    main()
  • But some kind of LaTeX remnant (from textFn?) is present on all timeline events in the resulting .png:
    • NOTE:
      • The remnants shown below are only present in the reulting .png, not the .pdf/.svg/.tex
  • image

latexmk issue

Hey there, never used laTex before, but I've installed it with homebrew on OS X. Running Python 3.6

Getting this error:

FileNotFoundError: [Errno 2] No such file or directory: 'latexmk': 'latexmk'

when trying to run the examples provided.

OSError: [Errno 22] Invalid argument on dt2milli

Hi, I had start testing your library with your examples, particularly the example 4, and everything is fine, but when I want to test my own dates it gives me the next error:

Traceback (most recent call last):
File "Timeline.py", line 56, in <module>
main()
File "Timeline.py", line 52, in main
tl = TimelineTex(items, options=options)
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\labella\timeline.py", line 419, in __init__
super().__init__(items, options=options, output_mode='tex')
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\labella\timeline.py", line 119, in __init__
self.init_axis(dicts)
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\labella\timeline.py", line 161, in init_axis
d3_extent(data, self.options['timeFn']))
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\labella\scale.py", line 342, in domain
num_domain = list(map(dt2milli, x))
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\labella\scale.py", line 11, in <lambda>
dt2milli = lambda x : x.timestamp() * 1000.0
OSError: [Errno 22] Invalid argument

I don't know what is wrong, it only happens when I change the date of the example data. Can you please help me to solve it? Thank you!
I'm using Windows 10 x64 with Python 3.6.4 x32, also I tested with python 3.6.3 x64 but the error is still there.

textStyle example

Had a look through the examples but could find one which showed how to adjust the font properties.

On the d3kit-timeline side they use a key as part of the options dict called textStyle:

textStyle: {
    'fill': '#fff',
    'text-decoration' : function(d){ return d.team==='BRA'? 'none': 'underline'},
    'font-weight': function(d){ return d.team==='BRA'? 700: 400}
  }

Tried following that structure with the below but didn't make any difference:

"textStyle": {
    "fill": "#000",
    "text-decoration": "underline",
    "font-weight": 700,
}

Is there maybe an example thay you could include in the examples directory that shows how to use this? Would be interested in changing the font as well.

Gantt chart

Is there any way to make something like this picture (events that are more than just a point) but with these nice labels?

import error

import error while importing TimelineTex
Already installed latex

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.