Flexitext is a Python library that makes it easier to draw text with multiple styles in Matplotlib

Overview

PyPI - Version Build Status Code style: black codecov

Introduction

Flexitext is a Python library that makes it easier to draw text with multiple styles in Matplotlib. This library is inspired and influenced by the R package ggtext.

Installation

Flexitext requires a working Python interpreter (3.7+). This library can be installed using pip:

pip install flexitext

Alternatively, you can install the development version from GitHub:

pip install git+https://github.com/tomicapretto/flexitext.git

Flexitext only requires Matplotlib version 3.4 or higher.

Overview

Albeit being inspired on ggtext, Flexitext does not use HTML, CSS, or Markdown to specify text styles. On the contrary, it implements a tag-based styling that looks similar to HTML tags, but is not exactly like HTML. These formatted strings consist of three components:

  • An opening tag that defines the styles to apply.
  • The text to be styled.
  • A closing tag, indicating the extent to which the styles in the opening tag apply.

Let's see an example:

This is blue text and this is regular text" ">
"
    
     This is blue text and this is regular text"
    
  • is the opening tag. Styles are key-value pairs separated by :. Multiple styles are separated by commas.
  • This is blue text is the text block. This text is going to be drawn using a font size of 16 and blue color.
  • is the closing tag. Only the text within the opening and the closing tags is formatted.

And finally we have and this is regular text. This is going to be drawn using the default style because it is not contained within any formatting tags.

Examples

The easiest way to use flexitext is through the flexitext function.

import matplotlib as mpl
import matplotlib.pyplot as plt

from flexitext import flexitext

mpl.rcParams['figure.facecolor'] = 'w'
fig, ax = plt.subplots(figsize=(9, 6))

text = "Normal text"
ax.text(0.5, 0.7, text, size=24, ha="center")

text = "
   
    Bold text"
   
flexitext(0.5, 0.6, text, ha="center")

text = "
   
    Italic text"
   
flexitext(0.5, 0.5, text, ha="center")

text = "
   
    Bold and 
    
     italic too!"
    
   
flexitext(0.5, 0.4, text, ha="center");

png

Styles can be nested

It is much easier now" flexitext(0.5, 0.6, text, ha="center"); ">
fig, ax = plt.subplots(figsize=(9, 6))

text = "
      
       It is much 
       
        easier 
        
         now"
        
       
      
flexitext(0.5, 0.6, text, ha="center");

png

A more convoluted example:

You can write using\n" " multiple formats,\nand linebreaks\n\n" " also bold text\n\n" " and why not italics too" ) fig, ax = plt.subplots(figsize=(9, 6)) flexitext(0.5, 0.5, text, ha="center", ma="center"); ">
text = (
    "
         
          You can write using
          \n"
         
    "
         
          multiple formats,
          \nand linebreaks
          \n
          \n"
         
    "
         
          also 
          
           bold text
           \n
           \n"
          
         
    "
         
          and why not 
          
           italics too"
          
         
)

fig, ax = plt.subplots(figsize=(9, 6))
flexitext(0.5, 0.5, text, ha="center", ma="center");

png

Use the figure fraction coordinates to write a formatted title.

A great chart showing\n" " the values for the " " blues and the reds" ) flexitext(0.025, 0.8, text, va="bottom", xycoords="figure fraction"); ">
fig, ax = plt.subplots(figsize=(9, 6))
fig.subplots_adjust(top=0.8, left=0.025)

x = [1, 2, 3]
y_blue = [2, 2.7, 4.5]
y_red = [1, 3, 2.5]


ax.scatter(x, y_blue, color="royalblue", s=120)
ax.scatter(x, y_red, color="crimson", s=120)

# Add flexitext
text = (
    "
        
         
          A 
          
           great chart showing
           \n"
          
         
        
    "
        
         the values for the "
        
    "
        
         blues and the 
         
          reds"
         
        
)
flexitext(0.025, 0.8, text, va="bottom", xycoords="figure fraction");

png

Notes

Flexitext only supports the following styles

  • alpha
  • backgroundcolor
  • color
  • family
  • name
  • size
  • style
  • weight

See Matplotlib's documentation for more information about their meaning and available values.

Flexitext logo is created with Flexitext and Matplotlib (see here).

Related work

  • highlight_text: Flexitext and highlight_text have similar goals. This library, highlight_text, allows you to customize more aspects of the highlighted text, such as the bounding box of the text or the border of the text with path effects. On the other hand, it requires you to pass a styles as a separated list of dictionaries instead of within the text.
Comments
  • Added Framework::Matplotlib to setup.cfg

    Added Framework::Matplotlib to setup.cfg

    Was having trouble finding this package, couldn't remember the name. Figure this would have helped me and make it slightly more discoverable. Also, please consider adding this package to https://matplotlib.org/mpl-third-party/

    opened by story645 6
  • About flexitext parameter

    About flexitext parameter "ha" and "va"

    Hello author, the ha and va parameters in the flexitext library do not seem to be consistent with those in ax.text. Set ha='center' in ax.text, the text of different lines will be aligned in the center, but this parameter seems to be invalid in flexitext (The alignment result is not quite consistent with the text). Setting ha='center' in flexitext is still left-aligned? The following is my code:

    `

    fig.subplots_adjust(top=0.8, left=0.025)
    x = [1, 2, 3]
    y_blue = [2, 2.7, 4.5]
    y_red = [1, 3, 2.5]
    ax.scatter(x, y_blue, color="royalblue", s=120)
    ax.scatter(x, y_red, color="crimson", s=120)
    # Add flexitext
    text = (
        "<name:Montserrat><size:24>A <weight:bold>great chart</> showing</>\n"
        "<size:18>the values for the "
        "<color:royalblue, weight:bold>blues</> and the <color:crimson, weight:bold>reds</></></>"
    )
    flexitext(0.5, 0.5, text, va="center", ha='center', ax=ax); #xycoords="figure fraction"
    ax.text(0.5, 0.2, text, va="center", ha='center',transform=ax.transAxes)
    plt.show()
    

    `

    image Is there a parameter in flexitext that can horizontally align the text of different lines in the center (even if the text size is inconsistent)?

    Thank you.

    opened by JiWenzheng 4
  • plt.subplots?

    plt.subplots?

    Hi, I want to use Flexitext to draw the text of subplots, but I find that parameter transform = axes. TransAxes is not supported. Is it possible to specify coordinate system in the future?

    opened by JiWenzheng 2
  • Several improvements and fixes

    Several improvements and fixes

    • Modify dev requirements and sort them alphabetically.
    • Add pyproject.toml where we set the length of the black formatter.
    • Flexitext now parses floats like 2. as 2.0. Previously it tried to parse two different numbers, resulting in an error.
    • Increase coverage to 100%.
    • Added changelog.
    opened by tomicapretto 1
  • Incompatibility with `constrained` layout?

    Incompatibility with `constrained` layout?

    I think I found a bug when using Matplotlib's constrained layout and flexitext. In this case, flexitext makes the layout very inconsistent if the window is resized, and different from what is expected. Here's some example code:

    import matplotlib.pyplot as plt
    from flexitext import flexitext
    
    fig, ax = plt.subplots(1, 2, figsize=(12, 6), layout="constrained")
    
    text1 = "<size:42, name:Carlito>Some<color:#11557c, weight:bold> text</></>"
    text2 = "<size:36, name:Lato, color:royalblue><weight:bold>Here</> too</>"
    
    flexitext(0.5, 0.5, text1, ha="center", ax=ax[0])
    flexitext(0.5, 0.5, text2, ha="center", ax=ax[1])
    
    fig.set_facecolor("w")
    # fig.savefig("example.png", dpi=300)
    plt.show()
    

    Here is a screenshot of the result: Screenshot from 2022-11-08 14-34-27

    After maximizing the window, and going back to its original size, the layout has changed: Screenshot from 2022-11-08 14-34-36

    Maximizing again, and going back to the original size: Screenshot from 2022-11-08 14-34-40

    Note that uncommenting fig.savefig("example.png", dpi=300) triggers a canvas draw and improves the layout for the given window size, but it doesn't seem to be what the layout would be without the flexitext.

    Expected layout: Screenshot from 2022-11-08 14-39-11

    Layout after a canvas draw: Screenshot from 2022-11-08 14-39-23

    What do you think?

    opened by guillaumedavidphd 7
Releases(v0.2.0)
  • v0.2.0(Mar 6, 2022)

    This release includes two relevant fixes/improvements:

    • Add mva argument to flexitext() which controls the vertical alignment of individual texts within the outer text box.
    • Improve backgroundcolor behavior. The backgroundcolor of one piece of text does not overlap other pieces of text by default now.
    Source code(tar.gz)
    Source code(zip)
  • v0.1.0(Sep 21, 2021)

kyle's vision of how datadog's python client should look

kyle's datadog python vision/proposal not for production use See examples/comprehensive.py for a mostly working example of the proposed API. 📈 🐶 ❤️

Kyle Verhoog 2 Nov 21, 2021
Visualize tensors in a plain Python REPL using Sparklines

Visualize tensors in a plain Python REPL using Sparklines

Shawn Presser 43 Sep 03, 2022
A customized interface for single cell track visualisation based on pcnaDeep and napari.

pcnaDeep-napari A customized interface for single cell track visualisation based on pcnaDeep and napari. 👀 Under construction You can get test image

ChanLab 2 Nov 07, 2021
A Graph Learning library for Humans

A Graph Learning library for Humans These novel algorithms include but are not limited to: A graph construction and graph searching class can be found

Richard Tjörnhammar 1 Feb 08, 2022
patchwork for matplotlib

patchworklib patchwork for matplotlib test code Preparation of example plots import seaborn as sns import numpy as np import pandas as pd #Bri

Mori Hideto 185 Jan 06, 2023
A gui application to visualize various sorting algorithms using pure python.

Sorting Algorithm Visualizer A gui application to visualize various sorting algorithms using pure python. Language : Python 3 Libraries required Tkint

Rajarshi Banerjee 19 Nov 30, 2022
Movies-chart - A CLI app gets the top 250 movies of all time from imdb.com and the top 100 movies from rottentomatoes.com

movies-chart This CLI app gets the top 250 movies of all time from imdb.com and

3 Feb 17, 2022
mysql relation charts

sqlcharts 自动生成数据库关联关系图 复制settings.py.example 重命名为settings.py 将数据库配置信息填入settings.DATABASE,目前支持mysql和postgresql 执行 python build.py -b,-b是读取数据库表结构,如果只更新匹

6 Aug 22, 2022
Tools for exploratory data analysis in Python

Dora Exploratory data analysis toolkit for Python. Contents Summary Setup Usage Reading Data & Configuration Cleaning Feature Selection & Extraction V

Nathan Epstein 599 Dec 25, 2022
Tandem Mass Spectrum Prediction with Graph Transformers

MassFormer This is the original implementation of MassFormer, a graph transformer for small molecule MS/MS prediction. Check out the preprint on arxiv

Röst Lab 13 Oct 27, 2022
Alternative layout visualizer for ZSA Moonlander keyboard

General info This is a keyboard layout visualizer for ZSA Moonlander keyboard (because I didn't find their Oryx or their training tool particularly us

10 Jul 19, 2022
A custom qq-plot for two sample data comparision

QQ-Plot 2 Sample Just a gist to include the custom code to draw a qq-plot in python when dealing with a "two sample problem". This means when u try to

1 Dec 20, 2021
Generate graphs with NetworkX, natively visualize with D3.js and pywebview

webview_d3 This is some PoC code to render graphs created with NetworkX natively using D3.js and pywebview. The main benifit of this approac

byt3bl33d3r 68 Aug 18, 2022
A simple python tool for explore your object detection dataset

A simple tool for explore your object detection dataset. The goal of this library is to provide simple and intuitive visualizations from your dataset and automatically find the best parameters for ge

GRADIANT - Centro Tecnolóxico de Telecomunicacións de Galicia 142 Dec 25, 2022
A Python package that provides evaluation and visualization tools for the DexYCB dataset

DexYCB Toolkit DexYCB Toolkit is a Python package that provides evaluation and visualization tools for the DexYCB dataset. The dataset and results wer

NVIDIA Research Projects 107 Dec 26, 2022
A simple agent-based model used to teach the basics of OOP in my lectures

Pydemic A simple agent-based model of a pandemic. This is used to teach basic principles of object-oriented programming to master students. It is not

Fabien Maussion 2 Jun 08, 2022
3D-Lorenz-Attractor-simulation-with-python

3D-Lorenz-Attractor-simulation-with-python Animação 3D da trajetória do Atrator de Lorenz, implementada em Python usando o método de Runge-Kutta de 4ª

Hevenicio Silva 17 Dec 08, 2022
Data parsing and validation using Python type hints

pydantic Data validation and settings management using Python type hinting. Fast and extensible, pydantic plays nicely with your linters/IDE/brain. De

Samuel Colvin 12.1k Jan 06, 2023
Visualization of the World Religion Data dataset by Correlates of War Project.

World Religion Data Visualization Visualization of the World Religion Data dataset by Correlates of War Project. Mostly personal project to famirializ

Emile Bangma 1 Oct 15, 2022
A Jupyter - Leaflet.js bridge

ipyleaflet A Jupyter / Leaflet bridge enabling interactive maps in the Jupyter notebook. Usage Selecting a basemap for a leaflet map: Loading a geojso

Jupyter Widgets 1.3k Dec 27, 2022