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
web application for flight log analysis & review

Flight Review This is a web application for flight log analysis. It allows users to upload ULog flight logs, and analyze them through the browser. It

PX4 Drone Autopilot 145 Dec 20, 2022
Alternative layout visualizer for ZSA Moonlander keyboard

General info This is a keyboard layout visualizer for ZSA Moonlander keyboard (because I didn't find their Oryx or their training tool particularly us

10 Jul 19, 2022
Streamlit dashboard examples - Twitter cashtags, StockTwits, WSB, Charts, SQL Pattern Scanner

streamlit-dashboards Streamlit dashboard examples - Twitter cashtags, StockTwits, WSB, Charts, SQL Pattern Scanner Tutorial Video https://ww

122 Dec 21, 2022
A napari plugin for visualising and interacting with electron cryotomograms.

napari-tomoslice A napari plugin for visualising and interacting with electron cryotomograms. Installation You can install napari-tomoslice via pip: p

3 Jan 03, 2023
Bcc2telegraf: An integration that sends ebpf-based bcc histogram metrics to telegraf daemon

bcc2telegraf bcc2telegraf is an integration that sends ebpf-based bcc histogram

Peter Bobrov 2 Feb 17, 2022
Create Badges with stats of Scratch User, Project and Studio. Use those badges in Github readmes, etc.

Scratch-Stats-Badge Create customized Badges with stats of Scratch User, Studio or Project. Use those badges in Github readmes, etc. Examples Document

Siddhesh Chavan 5 Aug 28, 2022
Scientific Visualization: Python + Matplotlib

An open access book on scientific visualization using python and matplotlib

Nicolas P. Rougier 8.6k Dec 31, 2022
The official colors of the FAU as matplotlib/seaborn colormaps

FAU - Colors The official colors of Friedrich-Alexander-Universität Erlangen-Nürnberg (FAU) as matplotlib / seaborn colormaps. We support the old colo

Machine Learning and Data Analytics Lab FAU 9 Sep 05, 2022
Scientific measurement library for instruments, experiments, and live-plotting

PyMeasure scientific package PyMeasure makes scientific measurements easy to set up and run. The package contains a repository of instrument classes a

PyMeasure 445 Jan 04, 2023
This is a Web scraping project using BeautifulSoup and Python to scrape basic information of all the Test matches played till Jan 2022.

Scraping-test-matches-data This is a Web scraping project using BeautifulSoup and Python to scrape basic information of all the Test matches played ti

Souradeep Banerjee 4 Oct 10, 2022
Gaphas is the diagramming widget library for Python.

Gaphas Gaphas is the diagramming widget library for Python. Gaphas is a library that provides the user interface component (widget) for drawing diagra

Gaphor 144 Dec 14, 2022
Sentiment Analysis application created with Python and Dash, hosted at socialsentiment.net

Social Sentiment Dash Application Live-streaming sentiment analysis application created with Python and Dash, hosted at SocialSentiment.net. Dash Tuto

Harrison 456 Dec 25, 2022
Info for The Great DataTas plot-a-thon

The Great DataTas plot-a-thon Datatas is organising a Data Visualisation competition: The Great DataTas plot-a-thon We will be using Tidy Tuesday data

2 Nov 21, 2021
Gallery of applications built using bqplot and widget libraries like ipywidgets, ipydatagrid etc.

bqplot Gallery This is a gallery of bqplot examples. View the gallery at https://bqplot.github.io/bqplot-gallery. Contributing new examples Clone this

8 Aug 23, 2022
✅ Today I Learn

Today I Learn EDA numpy_100ex numpy_0~10 airline_satisfaction_prediction BERT_naver_movie_classification NLP_prepare NLP_Tweet_Emotion_Recognition tex

Yeonghoo_Ahn 3 Dec 15, 2022
Create animated and pretty Pandas Dataframe or Pandas Series

Rich DataFrame Create animated and pretty Pandas Dataframe or Pandas Series, as shown below: Installation pip install rich-dataframe Usage Minimal exa

Khuyen Tran 92 Dec 26, 2022
A GUI for Pandas DataFrames

PandasGUI A GUI for analyzing Pandas DataFrames. Demo Installation Install latest release from PyPi: pip install pandasgui Install directly from Githu

Adam 2.8k Jan 03, 2023
PanGraphViewer -- show panenome graph in an easy way

PanGraphViewer -- show panenome graph in an easy way Table of Contents Versions and dependences Desktop-based panGraphViewer Library installation for

16 Dec 17, 2022
Plot-configurations for scientific publications, purely based on matplotlib

TUEplots Plot-configurations for scientific publications, purely based on matplotlib. Usage Please have a look at the examples in the example/ directo

Nicholas Krämer 487 Jan 08, 2023
Using SQLite within Python to create database and analyze Starcraft 2 units data (Pandas also used)

SQLite python Starcraft 2 English This project shows the usage of SQLite with python. To create, modify and communicate with the SQLite database from

1 Dec 30, 2021