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
Open-source demos hosted on Dash Gallery

Dash Sample Apps This repository hosts the code for over 100 open-source Dash apps written in Python or R. They can serve as a starting point for your

Plotly 2.7k Jan 07, 2023
Flipper Zero documentation repo

Flipper Zero Docs Participation To fix a bug or add something new to this repository, you need to open a pull-request. Also, on every page of the site

Flipper Zero (All Repositories will be public soon) 114 Dec 30, 2022
UNMAINTAINED! Renders beautiful SVG maps in Python.

Kartograph is not maintained anymore As you probably already guessed from the commit history in this repo, Kartograph.py is not maintained, which mean

1k Dec 09, 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
This is a Cross-Platform Plot Manager for Chia Plotting that is simple, easy-to-use, and reliable.

Swar's Chia Plot Manager A plot manager for Chia plotting: https://www.chia.net/ Development Version: v0.0.1 This is a cross-platform Chia Plot Manage

Swar Patel 1.3k Dec 13, 2022
A tool to plot and execute Rossmos's Formula, that helps to catch serial criminals using mathematics

Rossmo Plotter A tool to plot and execute Rossmos's Formula using python, that helps to catch serial criminals using mathematics Author: Amlan Saha Ku

Amlan Saha Kundu 3 Aug 29, 2022
🎨 Python Echarts Plotting Library

pyecharts Python ❤️ ECharts = pyecharts English README 📣 简介 Apache ECharts (incubating) 是一个由百度开源的数据可视化,凭借着良好的交互性,精巧的图表设计,得到了众多开发者的认可。而 Python 是一门富有表达

pyecharts 13.1k Jan 03, 2023
FairLens is an open source Python library for automatically discovering bias and measuring fairness in data

FairLens FairLens is an open source Python library for automatically discovering bias and measuring fairness in data. The package can be used to quick

Synthesized 69 Dec 15, 2022
Apache Superset is a Data Visualization and Data Exploration Platform

Superset A modern, enterprise-ready business intelligence web application. Why Superset? | Supported Databases | Installation and Configuration | Rele

The Apache Software Foundation 50k Jan 06, 2023
基于python爬虫爬取COVID-19爆发开始至今全球疫情数据并利用Echarts对数据进行分析与多样化展示。

COVID-19-Epidemic-Map 基于python爬虫爬取COVID-19爆发开始至今全球疫情数据并利用Echarts对数据进行分析与多样化展示。 觉得项目还不错的话欢迎给一个star! 项目的源码可以正常运行,各个库的版本、数据库的建表语句、运行过程中遇到的坑以及解决方式在笔记.md中都

31 Dec 15, 2022
Color scales in Python for humans

colorlover Color scales for humans IPython notebook: https://plot.ly/ipython-notebooks/color-scales/ import colorlover as cl from IPython.display impo

Plotly 146 Sep 25, 2022
Plot toolbox based on Matplotlib, simple and elegant.

Elegant-Plot Plot toolbox based on Matplotlib, simple and elegant. 绘制效果 绘制过程 数据准备 每种图标类型的目录下有data.csv文件,依据样例数据填入自己的数据。

3 Jul 15, 2022
Create HTML profiling reports from pandas DataFrame objects

Pandas Profiling Documentation | Slack | Stack Overflow Generates profile reports from a pandas DataFrame. The pandas df.describe() function is great

10k Jan 01, 2023
Productivity Tools for Plotly + Pandas

Cufflinks This library binds the power of plotly with the flexibility of pandas for easy plotting. This library is available on https://github.com/san

Jorge Santos 2.7k Dec 30, 2022
Altair extension for saving charts in a variety of formats.

Altair Saver This packge provides extensions to Altair for saving charts to a variety of output types. Supported output formats are: .json/.vl.json: V

Altair 85 Dec 09, 2022
Material for dataviz course at university of Bordeaux

Material for dataviz course at university of Bordeaux

Nicolas P. Rougier 50 Jul 17, 2022
Pyan3 - Offline call graph generator for Python 3

Pyan takes one or more Python source files, performs a (rather superficial) static analysis, and constructs a directed graph of the objects in the combined source, and how they define or use each oth

Juha Jeronen 235 Jan 02, 2023
Pretty Confusion Matrix

Pretty Confusion Matrix Why pretty confusion matrix? We can make confusion matrix by using matplotlib. However it is not so pretty. I want to make con

Junseo Ko 5 Nov 22, 2022
Plotting library for IPython/Jupyter notebooks

bqplot 2-D plotting library for Project Jupyter Introduction bqplot is a 2-D visualization system for Jupyter, based on the constructs of the Grammar

3.4k Dec 29, 2022
Type-safe YAML parser and validator.

StrictYAML StrictYAML is a type-safe YAML parser that parses and validates a restricted subset of the YAML specification. Priorities: Beautiful API Re

Colm O'Connor 1.2k Jan 04, 2023