Skip to main content

Legend creating and manipulation with ease for matplotlib

Project description

pypi version

When you want to create or adjust the legend in matplotlib, things can get dirty. LegendKit may solve your headache.

Features

  • Easy title placement and alignment
  • Layout for multiple legends
  • Easy colorbar

Installation

pip install legendkit

Usage

Any parameters you can use in legend or colorbar in matplotlib can also be used here.

Use it as the same old day

First create a plot

Usually, this is how you create the legend, the long title looks bad when it place at the center. But you can do nothing about it.

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 10, 0.1)
plt.plot(x, np.sin(x), color="r", label="sin")
plt.plot(x, np.sin(x), color="r", label="cos")
plt.legend(title="Trigonometry Functions")

With legendkit, things are easy, replace the default legend creation

from legendkit import legend
# plt.legend(title="Trigonometry Functions")
legend(title="Trigonometry Functions", title_align="left")

You can even create legend like this

legend(title="Trigonometry Functions", title_pos="left", ncol=2)

Create Colorbar

from legendkit import Colorbar, EllipseColorbar

Colorbar(vmin=0, vmax=10, title="Colorbar", title_align="left")
EllipseColorbar(vmin=0, vmax=10, title="Ellipse Colorbar", title_align="left")

Using preset legend

import matplotlib.pyplot as plt
from legendkit import CatLegend, SizeLegend

_, ax = plt.subplots()
CatLegend(["r", "g", "b"], ["Item 1", "Item 2", "Item 3"])
SizeLegend([i for i in range(101)])

Create a custom legend

If you want to create a custom legend, it's pretty easy to do it. Simple use an array to define it.

from legendkit import legend

legend(legend_items=[
    # (handle, label, config)
    ('square', 'Item 1', {'color': '#01949A'}),
    ('circle', 'Item 2', {'facecolor': '#004369', 
                          'edgecolor': '#DB1F48', 
                          'linewidth': 0.5}),
    ('rect', 'Item 3', {'color': '#E5DDC8'}),
    # Or you can have no config at all
    ('line', 'Item 4'),
])

Or you can use matplotlib legend handlers for richer definition.

LegendKit provides you with some predefined handlers to use out of the box.

  • The SquareItem will ensure square shape not matter how handle sizes are changed
  • The RectItem will ensure the rectangle shape even when handle sizes are the same
  • The LineItem is just a proxy to Line2D
from legendkit import legend
from legendkit.handles import SquareItem, CircleItem, RectItem, LineItem
from matplotlib.lines import Line2D

legend(
    handles=[SquareItem(), CircleItem(), RectItem(), LineItem(), Line2D([], [])], 
    labels=['Square', 'Circle', 'Rect', 'Line', 'Matplotlib Line'
])

If you want to use highly customized element as entry, please refer to here

Multiple legends layout

Sometimes you may want to group few legends together

  • vstack is used to stack legends vertically
  • hstack is used to stack legends horizontally
import matplotlib.pyplot as plt
from legendkit import legend
from legendkit.layout import vstack, hstack

_, ax = plt.subplots()

legend1 = legend(legend_items=[
    ('circle', 'The Moon', {'color': '#41729F'}),
], title="Earth's Moon")

legend2 = legend(legend_items=[
    ('circle', 'Deimos', {'color': '#3D550C'}),
    ('circle', 'Phobos', {'color': '#81B622'}),
], title="Mars' Moons")

legend3 = legend(legend_items=[
    ('circle', 'Io', {'color': '#FB4570'}),
    ('circle', 'Europa', {'color': '#FB6B90'}),
    ('circle', 'Ganymede', {'color': '#FB8DA0'}),
    ('circle', 'Callisto', {'color': '#EFEBE0'}),
], title="Moons of Jupyter")

legends = hstack([legend1, legend2, legend3], title="Moons in solar systems", spacing=10, frameon=True)
ax.add_artist(legends)  # Make sure you add it to the axes, or it won't be rendered

Grid layout with nested stack

You can create nested stack by stacking other stacks.

from legendkit.layout import vstack, hstack

s1 = vstack([])
s2 = vstack([])

final = hstack([s1, s2])

Understand layout in matplotlib legend

If you are familiar with css flexbox model, this is similar to how legend is layout internally in matplotlib.

A matplotlib legend have at least two parts, the handle and the label.

  • handle: The graphic to represent the item in the plot.
  • label: The text for the item.

Parameters to control the layout

The units used in the layout system is the same as font size.

Control the handle

  • handleheight: The height of the handle.
  • handlelength: The length of the handle.

Control the handle and the label:

  • handletextpad: the distance between the handle and the label.

Control between different items:

  • labelspacing: This control the distance between different legend items, it also controls the distance between title and items.
  • columnspacing: The distance between multiple columns of items.

Control the legend outer frame:

  • frameon: Toggle the on/off of the outer frame.
  • borderpad: The distance between the actual legend and the outer frame, apply for both x and y direction.
  • borderaxespad: The distance between the axes and the legend.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

legendkit-0.1.4.tar.gz (12.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

legendkit-0.1.4-py3-none-any.whl (12.7 kB view details)

Uploaded Python 3

File details

Details for the file legendkit-0.1.4.tar.gz.

File metadata

  • Download URL: legendkit-0.1.4.tar.gz
  • Upload date:
  • Size: 12.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.10.5

File hashes

Hashes for legendkit-0.1.4.tar.gz
Algorithm Hash digest
SHA256 03a35905456dcc6441b862cd9931f7b92a227a4767079f87835b44eb55d729de
MD5 b9df1dbfb3206147bd0d530f31c00c3a
BLAKE2b-256 17d5b2c03221fad91984af05250b94f531e1fdc5e64acf8bc0bfb6548d154b7d

See more details on using hashes here.

File details

Details for the file legendkit-0.1.4-py3-none-any.whl.

File metadata

  • Download URL: legendkit-0.1.4-py3-none-any.whl
  • Upload date:
  • Size: 12.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.10.5

File hashes

Hashes for legendkit-0.1.4-py3-none-any.whl
Algorithm Hash digest
SHA256 fe5a3b73bb9ff0891f1e0c3d902f7ce88f63ef13f1a65f530a44ead9f74d639e
MD5 1aeb71e1023f283ef26bd68f6259b3e0
BLAKE2b-256 1be32e75bd708e08d7e39735be781c873a0611261a7b90e72ed4c2c8c1c03b6a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page