CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-plotnine

A Grammar of Graphics for Python providing a declarative approach to data visualization similar to R's ggplot2

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

Plotnine

A comprehensive Python implementation of the Grammar of Graphics inspired by R's ggplot2. Plotnine enables developers and data scientists to create sophisticated data visualizations through a declarative and layered approach, building complex plots incrementally by explicitly mapping data variables to visual aesthetics and combining geometric objects, statistical transformations, coordinate systems, scales, and themes.

Package Information

  • Package Name: plotnine
  • Language: Python
  • Installation: pip install plotnine
  • Documentation: https://plotnine.readthedocs.io/en/stable

Core Imports

import plotnine as p9

Most common import pattern:

from plotnine import ggplot, aes, geom_point, theme_minimal

Full wildcard import (brings all functions into namespace):

from plotnine import *

Sample datasets:

from plotnine.data import mtcars, diamonds, economics

Basic Usage

import pandas as pd
from plotnine import ggplot, aes, geom_point, scale_x_continuous, theme_minimal, labs

# Create sample data
data = pd.DataFrame({
    'x': [1, 2, 3, 4, 5],
    'y': [2, 5, 3, 8, 7],
    'category': ['A', 'B', 'A', 'B', 'A']
})

# Create a basic scatter plot
plot = (ggplot(data, aes(x='x', y='y', color='category')) +
        geom_point(size=3) +
        scale_x_continuous(limits=(0, 6)) +
        theme_minimal() +
        labs(title='Basic Scatter Plot', x='X values', y='Y values'))

# Display the plot
print(plot)

# Save the plot
plot.save('my_plot.png', width=8, height=6, dpi=300)

Architecture

Plotnine follows the Grammar of Graphics layered approach where plots are built by combining these core components:

  • Data: The pandas DataFrame containing the data to visualize
  • Aesthetics (aes): Mappings between data variables and visual properties (x, y, color, size, etc.)
  • Geometries (geom_*): Visual representations of data (points, lines, bars, etc.)
  • Statistics (stat_*): Data transformations (binning, smoothing, summarizing)
  • Scales (scale_*): Control mappings from data space to aesthetic space
  • Coordinates (coord_*): Coordinate system transformations
  • Faceting (facet_*): Subplots based on data groupings
  • Themes (theme_*): Non-data plot appearance (colors, fonts, layout)

This modular design allows for infinite plot customization by composing these elements using the + operator.

Capabilities

Core Plot Construction

The foundation for all plotnine visualizations, including the main ggplot class, quick plotting functions, and save functionality.

class ggplot:
    def __init__(self, data=None, mapping=None): ...

def qplot(x=None, y=None, data=None, facets="", margins=False, geom="auto", 
          xlim=None, ylim=None, log=None, main=None, xlab=None, ylab=None, 
          asp=None, **kwargs): ...

def ggsave(filename, plot=None, width=6.4, height=4.8, dpi=100, **kwargs): ...

def save_as_pdf_pages(plots, filename=None, **kwargs): ...

Core Plotting

Aesthetic Mappings

Map data variables to visual properties like position, color, size, and shape. Essential for connecting your data to the visual representation.

def aes(x=None, y=None, **kwargs): ...

def after_stat(x): ...

def after_scale(x): ...

def stage(start=None, after_stat=None, after_scale=None): ...

Aesthetic Mappings

Geometric Objects

Visual representations that render your data as points, lines, bars, areas, and other shapes. Choose from over 50 geometric objects.

def geom_point(**kwargs): ...
def geom_line(**kwargs): ...
def geom_bar(**kwargs): ...
def geom_histogram(**kwargs): ...
def geom_boxplot(**kwargs): ...
def geom_smooth(**kwargs): ...

Geometric Objects

Statistical Transformations

Transform your data before visualization through binning, smoothing, density estimation, and other statistical operations.

def stat_count(**kwargs): ...
def stat_bin(**kwargs): ...
def stat_density(**kwargs): ...
def stat_smooth(**kwargs): ...
def stat_boxplot(**kwargs): ...

Statistical Transformations

Scales and Axes

Control how data values map to visual properties, including axis transformations, color palettes, and aesthetic ranges.

def scale_x_continuous(**kwargs): ...
def scale_y_continuous(**kwargs): ...
def scale_color_manual(**kwargs): ...
def scale_fill_gradient(**kwargs): ...
def xlim(*args): ...
def ylim(*args): ...

Scales and Axes

Coordinate Systems

Transform the coordinate system for specialized plot types like flipped axes, fixed aspect ratios, and polar coordinates.

def coord_cartesian(**kwargs): ...
def coord_flip(**kwargs): ...
def coord_fixed(**kwargs): ...
def coord_equal(**kwargs): ...
def coord_trans(**kwargs): ...

Coordinate Systems

Faceting

Create multiple panels to show different subsets of your data based on categorical variables.

def facet_wrap(facets, **kwargs): ...
def facet_grid(rows=None, cols=None, **kwargs): ...
def facet_null(): ...

Faceting

Position Adjustments

Adjust the position of geometric objects to handle overlapping data points or create specialized layouts.

def position_identity(): ...
def position_dodge(**kwargs): ...
def position_stack(**kwargs): ...
def position_fill(**kwargs): ...
def position_jitter(**kwargs): ...

Position Adjustments

Themes and Styling

Control the non-data aspects of your plot including colors, fonts, grid lines, and overall appearance.

def theme(**kwargs): ...
def theme_minimal(): ...
def theme_classic(): ...
def theme_dark(): ...
def element_text(**kwargs): ...
def element_line(**kwargs): ...

Themes and Styling

Labels and Annotations

Add titles, axis labels, legends, and text annotations to enhance plot clarity and communication.

def labs(**kwargs): ...
def ggtitle(title, subtitle=None): ...
def xlab(label): ...
def ylab(label): ...
def annotate(geom, **kwargs): ...

Labels and Annotations

Guides and Legends

Control the appearance and behavior of legends, color bars, and other plot guides.

def guides(**kwargs): ...
def guide_legend(**kwargs): ...
def guide_colorbar(**kwargs): ...

Guides and Legends

Watermarks

Add image watermarks to plots for branding and attribution purposes.

def watermark(filename, xo=None, yo=None, alpha=0.5, **kwargs): ...

Watermarks

Sample Datasets

Built-in datasets for examples, tutorials, and data exploration. Includes automotive, economic, biological, and statistical datasets commonly used in data visualization.

# Automotive data
mtcars: pandas.DataFrame  # Motor Trend car data
mpg: pandas.DataFrame     # Fuel economy data

# Economic data  
economics: pandas.DataFrame      # US economic time series
economics_long: pandas.DataFrame # Same data in long format

# Jewelry data
diamonds: pandas.DataFrame  # ~54,000 diamond prices and attributes

# Biological data
penguins: pandas.DataFrame  # Palmer penguins dataset
msleep: pandas.DataFrame    # Mammal sleep data

Sample Datasets

Common Data Types

# DataFrame expected structure
DataFrame = pandas.DataFrame  # With columns mappable to aesthetics

# Aesthetic mapping object
class aes(dict):
    """Aesthetic mappings between data and visual properties"""
    
# Plot object
class ggplot:
    """Main plot object that supports + operator for adding layers"""
    
# Layer components
class geom: """Base class for geometric objects"""
class stat: """Base class for statistical transformations"""  
class scale: """Base class for scales"""
class coord: """Base class for coordinate systems"""
class facet: """Base class for faceting"""
class theme: """Base class for themes"""

docs

aesthetic-mappings.md

coordinate-systems.md

core-plotting.md

faceting.md

geometric-objects.md

guides-and-legends.md

index.md

labels-and-annotations.md

position-adjustments.md

sample-datasets.md

scales-and-axes.md

statistical-transformations.md

themes-and-styling.md

watermarks.md

tile.json