Some useful extensions for Matplotlib.

Overview

mplx

Some useful extensions for Matplotlib.

PyPi Version PyPI pyversions GitHub stars Downloads

gh-actions codecov LGTM Code style: black

Contour plots for functions with discontinuities

plt.contour mplx.contour(max_jump=1.0)

Matplotlib has problems with contour plots of functions that have discontinuities. The software has no way to tell discontinuities and very sharp, but continuous cliffs apart, and contour lines will be drawn along the discontinuity.

mplx improves upon this by adding the parameter max_jump. If the difference between two function values in the grid is larger than max_jump, a discontinuity is assumed and no line is drawn. Similarly, min_jump can be used to highlight the discontinuity.

As an example, take the function imag(log(Z)) for complex values Z. Matplotlib's contour lines along the negative real axis are wrong.

import matplotlib.pyplot as plt
import numpy as np

import mplx

x = np.linspace(-2.0, 2.0, 100)
y = np.linspace(-2.0, 2.0, 100)

X, Y = np.meshgrid(x, y)
Z = X + 1j * Y

vals = np.imag(np.log(Z))

# plt.contour(X, Y, vals, levels=[-2.0, -1.0, 0.0, 1.0, 2.0])  # draws wrong lines
mplx.contour(X, Y, vals, levels=[-2.0, -1.0, 0.0, 1.0, 2.0], max_jump=1.0)
mplx.contour(X, Y, vals, levels=[0.0], min_jump=1.0, linestyles=":")

plt.gca().set_aspect("equal")
plt.show()

Relevant discussions:

License

This software is published under the MIT license.

Comments
  • Remove some typing hint to support older numpy ?

    Remove some typing hint to support older numpy ?

    Hello, I got an error ModuleNotFoundError: No module named 'numpy.typing' due to the typing hint from numpy.typing import ArrayLike.

    Would you mind remove this hint to support older numpy version like 1.19.* ? It seems no performance issue after remove it.

    opened by ProV1denCEX 5
  • Support for horizontal barchart

    Support for horizontal barchart

    This PR solves #30 by adding an alignment argument to show_bar_values defaulting to "vertical".

    I couldn't think of a robust way of determining the alignment automatically. Checking if the width of the bar is greater or lower than its height seemed a bit dodgy in some cases... I don't know. What do you think @nschloe ?

    Usage (adapted from README demo):

    import matplotlib.pyplot as plt
    import matplotx
    
    labels = ["Australia", "Brazil", "China", "Germany", "Mexico", "United\nStates"]
    vals = [21.65, 24.5, 6.95, 8.40, 21.00, 8.55]
    ypos = range(len(vals))
    
    
    with plt.style.context(matplotx.styles.dufte_bar):
        plt.barh(ypos, vals)
        plt.yticks(ypos, labels)
        matplotx.show_bar_values("{:.2f}", alignment="horizontal")
        plt.title("average temperature [°C]")
        plt.tight_layout()
        plt.show()
    

    Produces: Figure_1

    opened by RemDelaporteMathurin 3
  • Support for horizontal barchart

    Support for horizontal barchart

    matplotx.show_bar_values works perfectly with vertical bar charts but not with horizontal bar charts.

    These are often used with long text labels.

    import matplotlib.pyplot as plt
    import matplotx
    
    labels = ["Australia", "Brazil", "China", "Germany", "Mexico", "United\nStates"]
    vals = [21.65, 24.5, 6.95, 8.40, 21.00, 8.55]
    ypos = range(len(vals))
    
    with plt.style.context(matplotx.styles.dufte_bar):
        plt.barh(ypos, vals)
        plt.yticks(ypos, labels)
        matplotx.show_bar_values("{:.2f}")
        plt.title("average temperature [°C]")
        plt.tight_layout()
        plt.show()
    
    

    Produces: image

    I can write a PR and add a show_hbar_values() function that works with horizontal bar charts and produces: image

    Or it can also be an argument of matplotx.show_bar_value defaulting to "vertical" like show_bar_value(alignement="horizontal")

    What do you think @nschloe ?

    opened by RemDelaporteMathurin 2
  • Citation

    Citation

    Great package! Thank you so much it really helps!

    I will surely use this in my next paper/talk. How can I cite this package?

    Do you plan on adding a Zenodo DOI?

    Cheers Remi

    opened by RemDelaporteMathurin 2
  • Some styles are broken

    Some styles are broken

    Using the code example in the readme:

    import matplotlib.pyplot as plt
    import matplotx
    plt.style.use(matplotx.styles.ayu)
    

    I get this error:

    File ~/.conda/envs/.../lib/python3.10/site-packages/matplotlib/style/core.py:117, in use(style)
        115 for style in styles:
        116     if not isinstance(style, (str, Path)):
    --> 117         _apply_style(style)
        118     elif style == 'default':
        119         # Deprecation warnings were already handled when creating
        120         # rcParamsDefault, no need to reemit them here.
        121         with _api.suppress_matplotlib_deprecation_warning():
    
    File ~/.conda/envs/.../lib/python3.10/site-packages/matplotlib/style/core.py:62, in _apply_style(d, warn)
         61 def _apply_style(d, warn=True):
    ---> 62     mpl.rcParams.update(_remove_blacklisted_style_params(d, warn=warn))
    
    File ~/.conda/envs/.../lib/python3.10/_collections_abc.py:994, in MutableMapping.update(self, other, **kwds)
        992 if isinstance(other, Mapping):
        993     for key in other:
    --> 994         self[key] = other[key]
        995 elif hasattr(other, "keys"):
        996     for key in other.keys():
    
    File ~/.conda/envs/.../lib/python3.10/site-packages/matplotlib/__init__.py:649, in RcParams.__setitem__(self, key, val)
        647     dict.__setitem__(self, key, cval)
        648 except KeyError as err:
    --> 649     raise KeyError(
        650         f"{key} is not a valid rc parameter (see rcParams.keys() for "
        651         f"a list of valid parameters)") from err
    
    KeyError: 'dark is not a valid rc parameter (see rcParams.keys() for a list of valid parameters)'
    

    Lib versions:

    matplotlib-base           3.5.2           py310h5701ce4_1    conda-forge
    matplotx                  0.3.7                    pypi_0    pypi
    

    This happens with aura, ayu, github, gruvbox and others.

    Some of the themes working are: challenger_deep, dracula, dufte, nord, tab10

    opened by floringogianu 1
  • Support for subplots

    Support for subplots

    Related to the issue I opened. It seems that small changes already go quite a long way towards support for subplots. This does not yet work for the style.

    For the original code, everything was correctly calculated with the axes in mind, but then it was applied to plt instead of ax, even if an ax parameter was supplied for line_labels, it was still applied to plt.

    The code changes should have no effect when there are no subplots. When there are subplots, the code now offers better support.

    import matplotlib.pyplot as plt
    import matplotx
    import numpy as np
    
    # create data
    rng = np.random.default_rng(0)
    offsets = [1.0, 1.50, 1.60]
    labels = ["no balancing", "CRV-27", "CRV-27*"]
    names = ["Plot left", "Plot right"]
    x0 = np.linspace(0.0, 3.0, 100)
    y = [offset * x0 / (x0 + 1) + 0.1 * rng.random(len(x0)) for offset in offsets]
    
    fig, axes = plt.subplots(2,1)                                           
    
    for ax, name in zip(axes, names):                                                         
        with plt.style.context(matplotx.styles.dufte):
            for yy, label in zip(y, labels):
                ax.plot(x0, yy, label=label)                                
            ax.set_xlabel("distance [m]")                                   
        matplotx.ylabel_top(name)    
        matplotx.line_labels(ax=ax)
    

    Original code

    image

    New code

    image

    opened by mitchellvanzuijlen 1
  • dufte.legend allow plt.text kwargs

    dufte.legend allow plt.text kwargs

    To draw the legend dufte uses plt.text() https://github.com/nschloe/dufte/blob/main/src/dufte/main.py#L196

    plt.text() allows for additional kwargs to customize the text https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.text.html

    If possible, could you loop through the additional text kwargs to allow for a higher customizable legend?

    opened by exc4l 0
  • Improper ylabel_top placement

    Improper ylabel_top placement

    I've been using matplotx.ylabel_top and just noticed an issue with the label placement after setting the y tick labels explicitly. A working example is below.

    import numpy as np
    from seaborn import scatterplot
    import matplotx
    
    rng = np.random.default_rng(42)
    x = rng.random(100)
    y = -2*x + rng.normal(0, 0.5, 100)
    ax = scatterplot(
        x=x,
        y=y
    )
    ax.set_yticks([0, -1, -2])
    matplotx.ylabel_top('Example\nLabel')
    

    example

    i'm using

    numpy==1.23.4
    seaborn==0.12.1
    matplotx==0.3.10
    
    opened by markmbaum 0
  • First example images not properly clickable in readme

    First example images not properly clickable in readme

    I just came across this project, looks really neat. Especially the smooth contourf got me curious.

    I've noticed in the readme that (at least on firefox) if I click any of the three images, the link that opens (even with the "open image in new tab" context menu option) is https://github.com/nschloe/matplotx/blob/main/tests/dufte_comparison.py. In contrast, the contourf images open just fine, for instance.

    I assume the reason for this is the enclosing a tag for the first example: https://github.com/nschloe/matplotx/blob/c767b08ea91492b1db9626b8b2c8786b4bc99458/README.md?plain=1#L39

    In case this is not just a firefox thing, I would recommend trying to make the first three images clickable on their own right.

    opened by adeak 0
  • Adapt `line_labels` for `PolyCollections`

    Adapt `line_labels` for `PolyCollections`

    I'm keen on making a PR to adapt line_labels to make it work with fill_between objects (PolyCollection)

    This would be the usage and output:

    import matplotlib.pyplot as plt
    import matplotx
    import numpy as np
    
    x = np.linspace(0, 1)
    y1 = np.linspace(1, 2)
    y2 = np.linspace(2, 4)
    
    plt.fill_between(x, y1, label="label1")
    plt.fill_between(x, y1, y2, label="label1")
    
    matplotx.label_fillbetween()
    plt.show()
    

    image

    @nschloe would you be interested in this feature?

    opened by RemDelaporteMathurin 0
  • Support for subplots

    Support for subplots

    Perhaps this is already implemented and I'm just unable to find it. I think this package in general is great; very easy to use and very beautiful. Thank you for your time making it.

    I'm unable to get matplotx working properly when using subplots. Adapting the Clean line plots (dufte) example to include two subplots (side-by-side, or one-below-the-other) appears not to work.

    import matplotlib.pyplot as plt
    import matplotx
    import numpy as np
    
    # create data
    rng = np.random.default_rng(0)
    offsets = [1.0, 1.50, 1.60]
    labels = ["no balancing", "CRV-27", "CRV-27*"]
    x0 = np.linspace(0.0, 3.0, 100)
    y = [offset * x0 / (x0 + 1) + 0.1 * rng.random(len(x0)) for offset in offsets]
    
    fig, axes = plt.subplots(2,1)                                           # add subplots
    
    for ax in axes:                                                         # Let's make two identical subplots
        with plt.style.context(matplotx.styles.dufte):
            for yy, label in zip(y, labels):
                ax.plot(x0, yy, label=label)                                # changed plt. to ax.
            ax.set_xlabel("distance [m]")                                   # changed plt. to ax.
            matplotx.ylabel_top("voltage [V]")                              # move ylabel to the top, rotate
            matplotx.line_labels()                                          # line labels to the right
            #plt.show()                                                     # Including this adds the 'pretty axis' below the subplots.                             
    

    image

    opened by mitchellvanzuijlen 2
Releases(v0.3.10)
Owner
Nico Schlömer
Mathematics, numerical analysis, scientific computing, Python. Always interested in new problems.
Nico Schlömer
ecoglib: visualization and statistics for high density microecog signals

ecoglib: visualization and statistics for high density microecog signals This library contains high-level analysis tools for "topos" and "chronos" asp

1 Nov 17, 2021
Certificate generating and sending system written in Python.

Certificate Generator & Sender How to use git clone https://github.com/saadhaxxan/Certificate-Generator-Sender.git cd Certificate-Generator-Sender Add

Saad Hassan 11 Dec 01, 2022
EPViz is a tool to aid researchers in developing, validating, and reporting their predictive modeling outputs.

EPViz (EEG Prediction Visualizer) EPViz is a tool to aid researchers in developing, validating, and reporting their predictive modeling outputs. A lig

Jeff 2 Oct 19, 2022
Visualize and compare datasets, target values and associations, with one line of code.

In-depth EDA (target analysis, comparison, feature analysis, correlation) in two lines of code! Sweetviz is an open-source Python library that generat

Francois Bertrand 2.3k Jan 05, 2023
mysql relation charts

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

6 Aug 22, 2022
Turn a STAC catalog into a dask-based xarray

StackSTAC Turn a list of STAC items into a 4D xarray DataArray (dims: time, band, y, x), including reprojection to a common grid. The array is a lazy

Gabe Joseph 148 Dec 19, 2022
Generate visualizations of GitHub user and repository statistics using GitHub Actions.

GitHub Stats Visualization Generate visualizations of GitHub user and repository statistics using GitHub Actions. This project is currently a work-in-

JoelImgu 3 Dec 14, 2022
Data Visualization Guide for Presentations, Reports, and Dashboards

This is a highly practical and example-based guide on visually representing data in reports and dashboards.

Anton Zhiyanov 395 Dec 29, 2022
Create SVG drawings from vector geodata files (SHP, geojson, etc).

SVGIS Create SVG drawings from vector geodata files (SHP, geojson, etc). SVGIS is great for: creating small multiples, combining lots of datasets in a

Neil Freeman 78 Dec 09, 2022
Collection of scripts for making high quality beautiful math-related posters.

Poster Collection of scripts for making high quality beautiful math-related posters. The poster can have as large printing size as 3x2 square feet wit

Nattawut Phetmak 3 Jun 09, 2022
Python library that makes it easy for data scientists to create charts.

Chartify Chartify is a Python library that makes it easy for data scientists to create charts. Why use Chartify? Consistent input data format: Spend l

Spotify 3.2k Jan 01, 2023
Designed a greedy algorithm based on Markov sequential decision-making process in MATLAB/Python to optimize using Gurobi solver

Designed a greedy algorithm based on Markov sequential decision-making process in MATLAB/Python to optimize using Gurobi solver, the wheel size, gear shifting sequence by modeling drivetrain constrai

Sabbella Prasanna 1 Jan 11, 2022
Make scripted visualizations in blender

Scripted visualizations in blender The goal of this project is to script 3D scientific visualizations using blender. To achieve this, we aim to bring

Praneeth Namburi 10 Jun 01, 2022
Yata is a fast, simple and easy Data Visulaization tool, running on python dash

Yata is a fast, simple and easy Data Visulaization tool, running on python dash. The main goal of Yata is to provide a easy way for persons with little programming knowledge to visualize their data e

Cybercreek 3 Jun 28, 2021
🗾 Streamlit Component for rendering kepler.gl maps

streamlit-keplergl 🗾 Streamlit Component for rendering kepler.gl maps in a streamlit app. 🎈 Live Demo 🎈 Installation pip install streamlit-keplergl

Christoph Rieke 39 Dec 14, 2022
Generate "Jupiter" plots for circular genomes

jupiter Generate "Jupiter" plots for circular genomes Description Python scripts to generate plots from ViennaRNA output. Written in "pidgin" python w

Robert Edgar 2 Nov 29, 2021
a python function to plot a geopandas dataframe

Pretty GeoDataFrame A minimum python function (~60 lines) to draw pretty geodataframe. Based on matplotlib, shapely, descartes. Installation just use

haoming 27 Dec 05, 2022
Sky attention heatmap of submissions to astrometry.net

astroheat Installation Requires Python 3.6+, Tested with Python 3.9.5 Install library dependencies pip install -r requirements.txt The program require

4 Jun 20, 2022
CONTRIBUTIONS ONLY: Voluptuous, despite the name, is a Python data validation library.

CONTRIBUTIONS ONLY What does this mean? I do not have time to fix issues myself. The only way fixes or new features will be added is by people submitt

Alec Thomas 1.8k Dec 31, 2022
A library for bridging Python and HTML/Javascript (via Svelte) for creating interactive visualizations

A library for bridging Python and HTML/Javascript (via Svelte) for creating interactive visualizations

Anthropic 98 Dec 27, 2022