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
Statistical data visualization using matplotlib

seaborn: statistical data visualization Seaborn is a Python visualization library based on matplotlib. It provides a high-level interface for drawing

Michael Waskom 10.2k Dec 30, 2022
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
NorthPitch is a python soccer plotting library that sits on top of Matplotlib

NorthPitch is a python soccer plotting library that sits on top of Matplotlib.

Devin Pleuler 30 Feb 22, 2022
matplotlib: plotting with Python

Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. Check out our home page for more inform

Matplotlib Developers 16.7k Jan 8, 2023
Statistical data visualization using matplotlib

seaborn: statistical data visualization Seaborn is a Python visualization library based on matplotlib. It provides a high-level interface for drawing

Michael Waskom 8.1k Feb 13, 2021
:small_red_triangle: Ternary plotting library for python with matplotlib

python-ternary This is a plotting library for use with matplotlib to make ternary plots plots in the two dimensional simplex projected onto a two dime

Marc 611 Dec 29, 2022
Joyplots in Python with matplotlib & pandas :chart_with_upwards_trend:

JoyPy JoyPy is a one-function Python package based on matplotlib + pandas with a single purpose: drawing joyplots (a.k.a. ridgeline plots). The code f

Leonardo Taccari 462 Jan 2, 2023
A python package for animating plots build on matplotlib.

animatplot A python package for making interactive as well as animated plots with matplotlib. Requires Python >= 3.5 Matplotlib >= 2.2 (because slider

Tyler Makaro 394 Dec 18, 2022
matplotlib: plotting with Python

Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. Check out our home page for more inform

Matplotlib Developers 13.1k Feb 18, 2021
Statistical data visualization using matplotlib

seaborn: statistical data visualization Seaborn is a Python visualization library based on matplotlib. It provides a high-level interface for drawing

Michael Waskom 8.1k Feb 18, 2021
:small_red_triangle: Ternary plotting library for python with matplotlib

python-ternary This is a plotting library for use with matplotlib to make ternary plots plots in the two dimensional simplex projected onto a two dime

Marc 391 Feb 17, 2021
Joyplots in Python with matplotlib & pandas :chart_with_upwards_trend:

JoyPy JoyPy is a one-function Python package based on matplotlib + pandas with a single purpose: drawing joyplots (a.k.a. ridgeline plots). The code f

Leonardo Taccari 317 Feb 17, 2021
A python package for animating plots build on matplotlib.

animatplot A python package for making interactive as well as animated plots with matplotlib. Requires Python >= 3.5 Matplotlib >= 2.2 (because slider

Tyler Makaro 356 Feb 16, 2021
Painlessly create beautiful matplotlib plots.

Announcement Thank you to everyone who has used prettyplotlib and made it what it is today! Unfortunately, I no longer have the bandwidth to maintain

Olga Botvinnik 1.6k Jan 6, 2023
basemap - Plot on map projections (with coastlines and political boundaries) using matplotlib.

Basemap Plot on map projections (with coastlines and political boundaries) using matplotlib. ⚠️ Warning: this package is being deprecated in favour of

Matplotlib Developers 706 Dec 28, 2022
Easily convert matplotlib plots from Python into interactive Leaflet web maps.

mplleaflet mplleaflet is a Python library that converts a matplotlib plot into a webpage containing a pannable, zoomable Leaflet map. It can also embe

Jacob Wasserman 502 Dec 28, 2022
Design your own matplotlib stylefile interactively

Tired of playing with font sizes and other matplotlib parameters every time you start a new project or write a new plotting function? Want all you plots have the same style? Use matplotlib configuration files!

yobi byte 207 Dec 8, 2022
A Python library for plotting hockey rinks with Matplotlib.

Hockey Rink A Python library for plotting hockey rinks with Matplotlib. Installation pip install hockey_rink Current Rinks The following shows the cus

null 24 Jan 2, 2023
Print matplotlib colors

mplcolors Tired of searching "matplotlib colors" every week/day/hour? This simple script displays them all conveniently right in your terminal emulato

Brandon Barker 32 Dec 13, 2022