patchwork for matplotlib

Overview

patchworklib

patchwork for matplotlib

test code

Preparation of example plots

import seaborn as sns
import numpy  as np 
import pandas as pd 
    
#Brick1
fmri = sns.load_dataset("fmri")
brick1 = Brick("ax1", aspect=[1.5,1]) 
sns.lineplot(x="timepoint", y="signal", hue="region", 
    style="event", data=fmri, ax=brick1)
brick1.legend(bbox_to_anchor=(1.05, 0.8), loc='upper left')
brick1.set_title("Brick1")

#Brick2
brick2 = Brick("ax2", aspect=[1,2]) 
brick2.plot([1,2,3], [1,2,3], label="line1") 
brick2.plot([3,2,1], [1,2,3], label="line2") 
brick2.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
brick2.set_title("Brick2")

#Brick3
diamonds = sns.load_dataset("diamonds")
brick3 = Brick("ax3", (2,1))
sns.histplot(diamonds, x="price", hue="cut", multiple="stack",
palette="light:m_r", edgecolor=".3", linewidth=.5, log_scale=True,
    ax = brick3)
brick3.set_title("Brick3")

#Brick4
tips = sns.load_dataset("tips")
brick4 = Brick("ax4", (3,1)) 
sns.violinplot(data=tips, x="day", y="total_bill", hue="smoker",
    split=True, inner="quart", linewidth=1,
    palette={"Yes": "b", "No": ".85"},
    ax=brick4)
brick4.set_title("Brick4")

brick5 = Brick("ax5", (2,1)) 
rs = np.random.RandomState(365)
values = rs.randn(365, 4).cumsum(axis=0)
dates = pd.date_range("1 1 2016", periods=365, freq="D")
data = pd.DataFrame(values, dates, columns=["A", "B", "C", "D"])
data = data.rolling(7).mean()
sns.lineplot(data=data, palette="tab10", linewidth=2.5, ax=brick5)
brick5.set_title("Brick5") 

Patchwork demo

bricks1 = (brick1 | brick2 | brick3) / (brick4 | brick5) 
bricks1.savefig("test1.pdf")

bricks2 = (brick2 / brick1) | (brick5 / brick4 /brick3) 
bricks2.savefig("test2.pdf") 

Result

test1

test2

Comments
  • fix: proper p9 version check, support for >0.10

    fix: proper p9 version check, support for >0.10

    As stated in #25, patchworklib doesn't currently support the current plotnine release.

    The issue in place arises from the way plotnine's version is checked, since my understanding is that patchworklib supports plotnine releases starting from 0.8. The next major release (0.9) made some breaking changes which patchworklib handles by doing a simple string check to ensure whether the version is 0.8 or 0.9 so as to handle the ggplot drawing. This has, however, two unintended consequences:

    (1) Any plotnine release newer than 0.9 breaks patchworklib. (2) Any plotnine release with substrings containing 0.9 or 0.8 (such as a possible 0.10.8, for instance) will match the incorrect version and will be handled in the wrong manner.

    The fix is pretty trivial, and depends on the parse_version function of pkg_resources, which is in itself a dependency of setuptools that is already a dependency of patchworklib, so we aren't adding any extra dependencies.

    Comparisons are now made through the properly parsed versions, and any newer versions of plotnine should be handled appropiately now.

    By the way, thanks for the very useful library!

    opened by AlFontal 5
  • Iteratively generate plots and combine

    Iteratively generate plots and combine

    Hello!

    I am currently working on some code whereby I iteratively generate a list of plots using plotnine and I want to also be able to combine them all into one figure. Depending on when I run this code there may be a variable number of plots, and so I can not use the basic syntax of patchworklib.

    So my question is if there is a way with patchworklib to combine a list of plots together, instead of having to specify individual plot objects (ie "plot1 | plot2"). There doesn't seem to be a lot of options to do this using plotnine, but prefer it over the murky waters of matplotlib.

    Thanks for any help! Kurt

    opened by kyaki 4
  • Problem with theme_gray in plotnine (Can't support Plotnine 0.9.0)

    Problem with theme_gray in plotnine (Can't support Plotnine 0.9.0)

    Dear ponnhide,

    I would like firstly to thank you very much for creating and maintaining the patchworklib.

    In addition, I would like to comment about an issue I am getting when using it to arrange plotnine graphics. As an example, I will use the same one you have previously shared in: https://pypi.org/project/patchworklib/

    -- Code -- import patchworklib as pw from plotnine import * from plotnine.data import * g1 = pw.load_ggplot(ggplot(mtcars) + geom_point(aes("mpg", "disp")) + theme(figure_size=(2, 3))) g2 = pw.load_ggplot(ggplot(mtcars) + geom_boxplot(aes("gear", "disp", group = "gear")) + theme(figure_size=(2, 3))) g12 = g1 | g2 g12.savefig()

    -- Output --

    AttributeError Traceback (most recent call last) in <cell line: 4>() [2]from plotnine import * [3]from plotnine.data import * ----> [4]g1 = pw.load_ggplot(ggplot(mtcars) + geom_point(aes("mpg", "disp")) + theme(figure_size=(2, 3))) [5]g2 = pw.load_ggplot(ggplot(mtcars) + geom_boxplot(aes("gear", "disp", group = "gear")) + theme(figure_size=(2, 3))) [6]g12 = g1 | g2

    File C:\Users\rodrife\Anaconda3\lib\site-packages\patchworklib\patchworklib.py:401, in load_ggplot(ggplot, figsize) [399]ggplot._draw_breaks_and_labels() [400]ggplot._draw_watermarks() --> [401]ggplot._apply_theme() [403]if len(ggplot.axs) == 1: [404]ax = Brick(ax=ggplot.axs[0])

    File c:\Users\rodrife\Anaconda3\lib\site-packages\plotnine\ggplot.py:612, in ggplot._apply_theme(self) [608]def _apply_theme(self): [609]""" [610]Apply theme attributes to Matplotlib objects [611]""" --> [612]self.theme.apply_axs(self.axs) [613]self.theme.apply_figure(self.figure)

    AttributeError: 'theme_gray' object has no attribute 'apply_axs'

    I see it might be trying to apply theme attributes to Matplotlib objects, although in this case there is a plotnine object. However, since this is your example, it may be that I could have something wrong in my environment (e.g. plotnine or patchworklib). In any case, I would really appreciate any helping comment from your side.

    Thank you very much in advance! With my very best regards, Fermin

    enhancement 
    opened by Fermin-RH 4
  • How to turn off/modify legend in Patchworklib

    How to turn off/modify legend in Patchworklib

    Hello, thank you for your amazing tool so that I can make better pictures for my graduation thesis. I'm now having trouble on turning off/modifying the size of the legend in the combined pictures. I'm not a professional programmer so I'm not sure if it's my problem or if this function is not included in this package. I'll paste my code below:

    p1 = (
            ggplot(flight_01, aes(x='t_plot', y='FL1', shape="legend", color="legend"))
            + geom_point(alpha=0.5, size=0.5)
            + scale_x_datetime(labels=date_format('%H:%M'))
            + scale_color_manual(values=['tomato'], breaks=['trajectory'])
            + xlab("time [h]")
            + ylab("altitude x 10^2 [ft]")
            + ggtitle("Flight trajectory "+str(num[0])+"")
            + theme_gray()
            + theme(
                    legend_title=element_blank(),
                    figure_size=(12, 9),
                    legend_position='none',
                    legend_box='horizontal',
            )
    )
    
    p2 = (
            ggplot(flight_02, aes(x='t_plot', y='FL1', shape="legend", color="legend"))
            + geom_point(alpha=0.5, size=0.5)
            + scale_x_datetime(labels=date_format('%H:%M'))
            + scale_color_manual(values=['tomato'], breaks=['trajectory'])
            # + scale_x_datetime(breaks="30 minute", labels=date_format('%H:%M'))
            + xlab("time [h]")
            + ylab("altitude x 10^2 [ft]")
            + ggtitle("Flight trajectory "+str(num[1])+"")
            + theme_gray()
            + theme(
                    legend_title=element_blank(),
                    figure_size=(12, 9),
                    legend_position='right',
                    legend_box='horizontal',
                    legend_text=element_text(size=5)
            )
    )
    print(p1)
    print(p2)
    
    p1 = pw.load_ggplot(p1, figsize=(4, 3))
    p2 = pw.load_ggplot(p2, figsize=(4, 3))
    g1234 = p1|p2
    g1234.savefig("G:/DA/combi.png")
    

    As you can see I turn the legend off for p1 and keep only p2. I also turn off the word "legend" for p2 and make the text size smaller so that the width of the combined pic can be thinner.

    But in the combined pic g1234, the word "legend" is still there and the size of the legend remains the same as the title, which I didn't change at all. And the pics made by "print" are working as I wanted.

    Could you give me some advice on this? Thx a lot!

    enhancement 
    opened by BroDa1i 4
  • Handle seaborn plots generated based on figure-level function in patchworklib

    Handle seaborn plots generated based on figure-level function in patchworklib

    Seaborn plots generated based on figure-level function cannot be handled as matplotlib subplots. The issue is mentioned in some places (https://github.com/mwaskom/seaborn/issues/2666, https://github.com/mwaskom/seaborn/issues/2059). Now, patchworklib can import the following plots as Bricks class objects and align them with other plots.

    • [x] pairplot
    • [x] relplot
    • [x] jointplot
    • [x] catplot
    • [x] displot

    However, it still cannot handle clustermap plots based on clustermap function.

    opened by ponnhide 4
  • Plotnine legend position is reset after using patchworklib

    Plotnine legend position is reset after using patchworklib

    I've noticed that my original ggplot legend position is not maintained after patching together. I used...

    • theme(legend_position=(.5, -0.02), legend_direction='horizontal')

    ...to position it underneath each individual ggplot before combining with patchworklib. However, after patching together, the legend goes back to the right side for every sub-plot.

    Is this related to the same issue as in #15? Thanks.

    opened by iddryg 3
  • Label size is not reserved from ggplot

    Label size is not reserved from ggplot

    Hi, thanks for this cool library!

    I noticed that several set_*label calls in load_ggplot doesn't pass on any other style settings such as font size so the axis title always ends up being size 12.

    Let me know if you need more information on this.

    opened by ChenghaoMou 3
  • The size of the subgraph will automatically change

    The size of the subgraph will automatically change

    patchworklib has saved me a lot of effort consumed in the layout.

    But recently I found that in some special cases it automatically modifies the size of the subgraph.

    ls_ax = []
    for i in range(10):
        ls_ax.append(pw.Brick(f"ax{i}", (3, 3)))
    ls_ax = [ls_ax[:3], ls_ax[3:6], ls_ax[6:9], ls_ax[9]]
    _axs = [reduce(lambda x,y: x|y, z) for z in ls_ax[:-1]]
    _axs = reduce(lambda x,y: x/y, _axs)
    _axs = _axs['ax6'] / ls_ax[-1]
    
    _axs.savefig()
    

    output

    opened by liuzj039 3
  • Replace final plotnine version check.

    Replace final plotnine version check.

    Based on the work of @AlFontal's commit #26 in response to issue #25, replace the final plotnine version check as it still failed when using plotnine's facet_grid and facet_wrap.

    The failure can be seen in the 'subplots for plotnine' Colab linked from the ReadMe.

    Colab Result: image

    The failure can also be reproduced with the example below:

    import pandas as pd
    import patchworklib as pw
    import plotnine as p9
    
    df = pd.DataFrame({'a': range(10), 'b': ['x', 'y']*5})
    
    work_around = False
    if work_around:
    	df1 = df.query('b == "x"')
    	g1 = (p9.ggplot(df1, p9.aes(x=df1.index, y='a')) 
    		+ p9.geom_line()
    		)
    	df2 = df.query('b == "y"')
    	g2 = (p9.ggplot(df2, p9.aes(x=df2.index, y='a')) 
    		+ p9.geom_line()
    		)
    	
    	success1 = pw.load_ggplot(g1)
    	success2 = pw.load_ggplot(g2)
    
    	g = success1|success2
    	g.savefig('success')
    else:
    	g = (p9.ggplot(df, p9.aes(x=df.index, y='a', colour='factor(b)')) 
    		+ p9.geom_line()
    		+ p9.facet_wrap('~b')
    		)
    	failure = pw.load_ggplot(g)
    	# Produces error: Type Error: argument of type 'Version' is not iterable
    	print(g)
    

    From my testing it now works with facet_grid and facet_wrap.

    Please excuse any incompetence as I am a novice.

    opened by NWNHT 2
  • Is there a specific option to configure to make spyder IDE display images in The Plots pane?

    Is there a specific option to configure to make spyder IDE display images in The Plots pane?

    Hi, ponnhide. When I use your package and plotnine in spyder IDE, I find that the generated plots are all in the console window and not in the plots pane. But when using only plotnine, the image is displayed in the plots pane.

    opened by CaoTianze 2
  • Can't support Plotnine 0.9.0

    Can't support Plotnine 0.9.0

    When I use patchworklib with Plotnine 0.9.0,it reminds me “AttributeError: 'theme_gray' object has no attribute 'apply_axs'”.But I revert plotnine to 0.8.0,patchworklib work normally.

    opened by pyqf66 2
  • Add PyPI release gh actions workflow

    Add PyPI release gh actions workflow

    This PR is created to resolve issue #21.

    GitHub Actions Workflow for publishing packages to PyPI for release on GitHub.


    :warning: To run this workflow, you will need to set up a secret key (PYPI_USERNAME, PYPI_PASSWORD) to access PyPI in advance.

    Secrect Key Setting URL: https://github.com/ponnhide/patchworklib/settings/secrets/actions

    github_pypi_secret_key

    opened by moshi4 0
  • Publish this through conda-forge

    Publish this through conda-forge

    Hi, it would be very cool to have a conda-forge package of this:

    • https://conda-forge.org/docs/user/introduction.html
    • https://conda-forge.org/docs/maintainer/adding_pkgs.html#the-staging-process

    I created a draft PR here: https://github.com/conda-forge/staged-recipes/pull/21603

    opened by Hoeze 0
  • Usage with matplotlib PdfPages

    Usage with matplotlib PdfPages

    Hey,

    amazing package making life so much easier :)

    I was wondering if it is possible to use patchworklib with PdfPages from matplotlib?

    I am generating plots using plotnine, then assemble two side by side using patchworklib and then I would like to export a list of the patchwork brick objects to a multi-page PDF. So far I did not figure out how to properly chain the commands, so I was wondering if it is possible in the first place?

    Thanks, Artyom

    opened by ArtiVlasov 1
  • Create tests and run them on CI

    Create tests and run them on CI

    Would make me more comfortable depending on this package in a production environment if there was a test suite.

    I'm not quite sure how to test everything, but some tests that run the patchwork examples would probably go a good distance in catching different errors that arise. The cowpatch tests might be of some inspiration.

    You can configure github actions to run the tests on every commit / PR as well as on a scheduled basis to detect for example if a dependency update breaks something. Happy to help set up the actions.

    opened by dhimmel 0
  • Use GitHub Actions to publish releases to PyPI for complete git tags

    Use GitHub Actions to publish releases to PyPI for complete git tags

    Thanks for making frequent releases of this package, as seen on PyPI. Noting that there are only two git tags currently. Therefore it's hard to know which commits have made it into which releases.

    Have you using GitHub Actions to deploy to PyPI? This way whenever you create a release on GitHub at https://github.com/ponnhide/patchworklib/releases/new, it will automatically be deployed to PyPI. You'll get the git tag automatically. Also you can put release notes on the GitHub Release (rather than in the readme).

    An example workflow to do this at https://github.com/manubot/manubot/blob/a2ba5780fbbdef9dfc063180b98e6dea500aec48/.github/workflows/release.yml.

    Happy to help with this if you're interested! Just found this package and excited for something that can combine python plots!

    opened by dhimmel 3
Releases(v0.4.2)
Owner
Mori Hideto
Mori Hideto
MPL Plotter is a Matplotlib based Python plotting library built with the goal of delivering publication-quality plots concisely.

MPL Plotter is a Matplotlib based Python plotting library built with the goal of delivering publication-quality plots concisely.

Antonio López Rivera 162 Nov 11, 2022
Lime: Explaining the predictions of any machine learning classifier

lime This project is about explaining what machine learning classifiers (or models) are doing. At the moment, we support explaining individual predict

Marco Tulio Correia Ribeiro 10.3k Dec 29, 2022
simple tool to paint axis x and y

simple tool to paint axis x and y

G705 1 Oct 21, 2021
AB-test-analyzer - Python class to perform AB test analysis

AB-test-analyzer Python class to perform AB test analysis Overview This repo con

13 Jul 16, 2022
Compute and visualise incidence (reworking of the original incidence package)

incidence2 incidence2 is an R package that implements functions and classes to compute, handle and visualise incidence from linelist data. It refocuss

15 Nov 22, 2022
股票行情实时数据接口-A股,完全免费的沪深证券股票数据-中国股市,python最简封装的API接口

股票行情实时数据接口-A股,完全免费的沪深证券股票数据-中国股市,python最简封装的API接口,包含日线,历史K线,分时线,分钟线,全部实时采集,系统包括新浪腾讯双数据核心采集获取,自动故障切换,STOCK数据格式成DataFrame格式,可用来查询研究量化分析,股票程序自动化交易系统.为量化研究者在数据获取方面极大地减轻工作量,更加专注于策略和模型的研究与实现。

dev 572 Jan 08, 2023
An application that allows you to design and test your own stock trading algorithms in an attempt to beat the market.

StockBot is a Python application for designing and testing your own daily stock trading algorithms. Installation Use the

Ryan Cullen 280 Dec 19, 2022
Easily configurable, chart dashboards from any arbitrary API endpoint. JSON config only

Flask JSONDash Easily configurable, chart dashboards from any arbitrary API endpoint. JSON config only. Ready to go. This project is a flask blueprint

Chris Tabor 3.3k Dec 31, 2022
Drag’n’drop Pivot Tables and Charts for Jupyter/IPython Notebook, care of PivotTable.js

pivottablejs: the Python module Drag’n’drop Pivot Tables and Charts for Jupyter/IPython Notebook, care of PivotTable.js Installation pip install pivot

Nicolas Kruchten 512 Dec 26, 2022
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
This is a super simple visualization toolbox (script) for transformer attention visualization ✌

Trans_attention_vis This is a super simple visualization toolbox (script) for transformer attention visualization ✌ 1. How to prepare your attention m

Mingyu Wang 3 Jul 09, 2022
Visualizations of linear algebra algorithms for people who want a deep understanding

Visualising algorithms on symmetric matrices Examples QR algorithm and LR algorithm Here, we have a GIF animation of an interactive visualisation of t

ogogmad 3 May 05, 2022
Example Code Notebooks for Data Visualization in Python

This repository contains sample code scripts for creating awesome data visualizations from scratch using different python libraries (such as matplotli

Javed Ali 27 Jan 04, 2023
Complex heatmaps are efficient to visualize associations between different sources of data sets and reveal potential patterns.

Make Complex Heatmaps Complex heatmaps are efficient to visualize associations between different sources of data sets and reveal potential patterns. H

Zuguang Gu 973 Jan 09, 2023
Simple implementation of Self Organizing Maps (SOMs) with rectangular and hexagonal grid topologies

py-self-organizing-map Simple implementation of Self Organizing Maps (SOMs) with rectangular and hexagonal grid topologies. A SOM is a simple unsuperv

Jonas Grebe 1 Feb 10, 2022
Cryptocurrency Centralized Exchange Visualization

This is a simple one that uses Grafina to visualize cryptocurrency from the Bitkub exchange. This service will make a request to the Bitkub API from your wallet and save the response to Postgresql. G

Popboon Mahachanawong 1 Nov 24, 2021
Learning Convolutional Neural Networks with Interactive Visualization.

CNN Explainer An interactive visualization system designed to help non-experts learn about Convolutional Neural Networks (CNNs) For more information,

Polo Club of Data Science 6.3k Jan 01, 2023
Interactive Data Visualization in the browser, from Python

Bokeh is an interactive visualization library for modern web browsers. It provides elegant, concise construction of versatile graphics, and affords hi

Bokeh 17.1k Dec 31, 2022
Statistics and Visualization of acceptance rate, main keyword of CVPR 2021 accepted papers for the main Computer Vision conference (CVPR)

Statistics and Visualization of acceptance rate, main keyword of CVPR 2021 accepted papers for the main Computer Vision conference (CVPR)

Hoseong Lee 78 Aug 23, 2022
View part of your screen in grayscale or simulated color vision deficiency.

monolens View part of your screen in grayscale or filtered to simulate color vision deficiency. Watch the demo on YouTube. Install with pip install mo

Hans Dembinski 31 Oct 11, 2022