plotnine

repository·main·Indexed 26 days ago

https://github.com/has2k1/plotnine

A Python implementation of the 'grammar of graphics' based on ggplot2. It allows users to build complex, layered visualizations by mapping dataframe variables to aesthetic properties using components such as ggplot, aes, geoms, stats, facets, and themes via the + operator.

Tokens
5.8K
Snippets
4
Records
52
Agent score
89%

What's inside plotnine

  1. Install development version of plotnine

    main

    To install the development version directly from GitHub, use pip with the git URL. If you are working with images, you may also want to install oxipng (via Homebrew or Cargo) as a test image optimizer.

    $ pip install git+https://github.com/has2k1/plotnine.git
    $ brew install oxipng   # Test image optimiser (OR `cargo install oxipng`)
  2. Install plotnine

    main

    You can install plotnine using pip, conda, or pixi. For most users, the standard pip installation is sufficient. If you need optional dependencies, use the [extra] flag.

    # Using pip
    $ pip install plotnine             # standard installation
    $ pip install 'plotnine[extra]'    # includes extra/optional packages
    
    # Or using conda
    $ conda install -c conda-forge plotnine
    
    # Or using pixi
    $ pixi init name-of-my-project
    $ cd name-of-my-project
    $ pixi add python plotnine
  3. Create plots with the grammar of graphics

    main

    plotnine implements a grammar of graphics inspired by ggplot2. You compose plots by mapping dataframe variables to visual characteristics (position, color, size, etc.) using ggplot() and adding layers with +.

    from plotnine import *
    from plotnine.data import mtcars
    
    # Example: Scatter plot with color mapping and a smoothed linear model
    (
        ggplot(mtcars, aes("wt", "mpg", color="factor(gear)"))
        + geom_point()
        + stat_smooth(method="lm")
        + facet_wrap("gear")
        + theme_tufte()
    )
  4. Core components of plotnine

    main

    The plotnine package provides a Python implementation of the Grammar of Graphics. You can import all major components directly from the top-level plotnine module to build plots using ggplot().

    Key functional groups available via from plotnine import ... include:

    • Core: ggplot, qplot, ggsave, save_as_pdf_pages.
    • Mappings & Aesthetics: aes, after_scale, after_stat, stage.
    • Geometries (Geoms): geom_point, geom_line, geom_bar, geom_boxplot, etc.
    • Scales: scale_color_manual, scale_fill_continuous, scale_x_log10, scale_y_discrete, etc.
    • Facets: facet_grid, facet_wrap, facet_null.
    • Coordinates: coord_cartesian, coord_flip, coord_fixed.
    • Stats: stat_smooth, stat_bin, stat_count, etc.
    • Themes: theme_minimal, theme_bw, theme_classic, and individual element_* components.
    • Labels & Guides: labs, xlab, ylab, ggtitle, guides, guide_legend.
  5. Add layers to a ggplot object

    main

    You can add a layer or a collection of Layers to a ggplot object using the + operator (via the __radd__ method).

    (ggplot(data, aes(x='x', y='y'))
     + geom_point()  # Adds a single layer
     + geom_line())  # Adds another layer
  6. Configure figure formats and facet layouts

    main

    Use the following type definitions to configure plot output and layout:

    • Figure formats: FigureFormat accepts `
  7. Configure text and guide justification

    main

    Control the alignment of text and guides using these types:

    • Justification: Combines HorizontalJustification (`
  8. Ensure consistent scale limits in animations

    main

    When creating a PlotnineAnimation, all frames must share identical scale limits. If a frame's scale limits differ from the first frame, a PlotnineError will be raised.

    To prevent this, manually define the limits for each aesthetic used in your plots. For example, if your animation involves a moving point on the x-axis, ensure every ggplot object in the plots list uses the same scale_x_continuous(limits=(min, max)) configuration.

  9. Create plots with plotnine

    main

    plotnine provides a grammar of graphics implementation for Python. You can build plots by layering components like ggplot, aes (aesthetics), geom_* (geometries), stat_* (statistical transformations), facet_* (faceting), and theme (visual styling) using the + operator.

    from plotnine import (
        aes,
        facet_wrap,
        geom_point,
        ggplot,
        stat_smooth,
        theme,
        theme_tufte,
        theme_xkcd,
    )
    from plotnine.data import mtcars
    
    # Basic scatter plot with custom theme settings
    p1 = (
        ggplot(mtcars, aes("wt", "mpg"))
        + geom_point()
        + theme(figure_size=(6, 4), dpi=300)
    )
    
    # Adding color aesthetics
    p2 = p1 + aes(color="factor(gear")
    
    # Adding a statistical smooth layer (linear model)
    p3 = p2 + stat_smooth(method="lm")
    
    # Faceting the plot by a variable
    p4 = p3 + facet_wrap("gear")
    
    # Applying specialized themes like xkcd or Tufte
    p5 = p4 + theme_xkcd()
    p5alt = p4 + theme_tufte()
    
    # Save the plots
    p5.save("readme-image-5.png")
  10. Implement custom column transformations

    main

    To create a custom transformation for a column, you can implement the PTransform protocol or use the TransformCol type alias.

    • TransformCol: A callable that takes a FloatSeries and returns a FloatSeries or FloatArray.
    • PTransform: A protocol requiring a __call__ method that accepts a TFloatArrayLike and returns a TFloatArrayLike.