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
Project coded in Python using Pandas to look at changes in chase% for batters facing a pitcher first time through the order vs. thrid time

Project coded in Python using Pandas to look at changes in chase% for batters facing a pitcher first time through the order vs. thrid time

Jason Kraynak 1 Jan 07, 2022
Lightweight, extensible data validation library for Python

Cerberus Cerberus is a lightweight and extensible data validation library for Python. v = Validator({'name': {'type': 'string'}}) v.validate({

eve 2.9k Dec 27, 2022
Some method of processing point cloud

Point-Cloud Some method of processing point cloud inversion the completion pointcloud to incomplete point cloud Some model of encoding point cloud to

Tan 1 Nov 19, 2021
A python script and steps to display locations of peers connected to qbittorrent

A python script (along with instructions) to display the locations of all the peers your qBittorrent client is connected to in a Grafana worldmap dash

62 Dec 07, 2022
哔咔漫画window客户端,界面使用PySide2,已实现分类、搜索、收藏夹、下载、在线观看、waifu2x等功能。

picacomic-windows 哔咔漫画window客户端,界面使用PySide2,已实现分类、搜索、收藏夹、下载、在线观看等功能。 功能介绍 登陆分流,还原安卓端的三个分流入口 分类,搜索,排行,收藏夹使用同一的逻辑,滚轮下滑自动加载下一页,双击打开 漫画详情,章节列表和评论列表 下载功能,目

1.8k Dec 31, 2022
ICS-Visualizer is an interactive Industrial Control Systems (ICS) network graph that contains up-to-date ICS metadata

ICS-Visualizer is an interactive Industrial Control Systems (ICS) network graph that contains up-to-date ICS metadata (Name, company, port, user manua

QeeqBox 2 Dec 13, 2021
阴阳师后台全平台(使用网易 MuMu 模拟器)辅助。支持御魂,觉醒,御灵,结界突破,秘闻副本,地域鬼王。

阴阳师后台全平台辅助 Python 版本:Python 3.8.3 模拟器:网易 MuMu | 雷电模拟器 模拟器分辨率:1024*576 显卡渲染模式:兼容(OpenGL) 兼容 Windows 系统和 MacOS 系统 思路: 利用 adb 截图后,使用 opencv 找图找色,模拟点击。使用

简讯 27 Jul 09, 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
Python & Julia port of codes in excellent R books

X4DS This repo is a collection of Python & Julia port of codes in the following excellent R books: An Introduction to Statistical Learning (ISLR) Stat

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

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

dev 572 Jan 08, 2023
A python visualization of the A* path finding algorithm

A python visualization of the A* path finding algorithm. It allows you to pick your start, end location and make obstacles and then view the process of finding the shortest path. You can also choose

Kimeon 4 Aug 02, 2022
Generate SVG (dark/light) images visualizing (private/public) GitHub repo statistics for profile/website.

Generate daily updated visualizations of GitHub user and repository statistics from the GitHub API using GitHub Actions for any combination of private and public repositories, whether owned or contri

Adam Ross 2 Dec 16, 2022
Advanced hot reloading for Python

The missing element of Python - Advanced Hot Reloading Details Reloadium adds hot reloading also called "edit and continue" functionality to any Pytho

Reloadware 1.9k Jan 04, 2023
The windML framework provides an easy-to-use access to wind data sources within the Python world, building upon numpy, scipy, sklearn, and matplotlib. Renewable Wind Energy, Forecasting, Prediction

windml Build status : The importance of wind in smart grids with a large number of renewable energy resources is increasing. With the growing infrastr

Computational Intelligence Group 125 Dec 24, 2022
Visualization Website by using Dash and Heroku

Visualization Website by using Dash and Heroku You can visit the website https://payroll-expense-analysis.herokuapp.com/ In this project, I am interes

YF Liu 1 Jan 14, 2022
Tidy data structures, summaries, and visualisations for missing data

naniar naniar provides principled, tidy ways to summarise, visualise, and manipulate missing data with minimal deviations from the workflows in ggplot

Nicholas Tierney 611 Dec 22, 2022
Use Perspective to create the chart for the trader’s dashboard

Task Overview | Installation Instructions | Link to Module 3 Introduction Experience Technology at JP Morgan Chase Try out what real work is like in t

Abdulazeez Jimoh 1 Jan 22, 2022
A small tool to test and visualize protein embeddings and amino acid proportions.

polyprotein_stats A small tool to test and visualize protein embeddings and amino acid proportions. Currently deployed on streamlit.io. Given a set of

2 Jan 07, 2023
A Python Library for Self Organizing Map (SOM)

SOMPY A Python Library for Self Organizing Map (SOM) As much as possible, the structure of SOM is similar to somtoolbox in Matlab. It has the followin

Vahid Moosavi 497 Dec 29, 2022
Data Visualizations for the #30DayChartChallenge

The #30DayChartChallenge This repository contains all the charts made for the #30DayChartChallenge during the month of April. This project aims to exp

Isaac Arroyo 7 Sep 20, 2022