A Grammar of Graphics for Python providing a declarative approach to data visualization similar to R's ggplot2
npx @tessl/cli install tessl/pypi-plotnine@0.15.0A 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.
pip install plotnineimport plotnine as p9Most common import pattern:
from plotnine import ggplot, aes, geom_point, theme_minimalFull wildcard import (brings all functions into namespace):
from plotnine import *Sample datasets:
from plotnine.data import mtcars, diamonds, economicsimport 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)Plotnine follows the Grammar of Graphics layered approach where plots are built by combining these core components:
This modular design allows for infinite plot customization by composing these elements using the + operator.
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): ...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): ...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): ...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): ...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): ...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): ...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(): ...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): ...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): ...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): ...Control the appearance and behavior of legends, color bars, and other plot guides.
def guides(**kwargs): ...
def guide_legend(**kwargs): ...
def guide_colorbar(**kwargs): ...Add image watermarks to plots for branding and attribution purposes.
def watermark(filename, xo=None, yo=None, alpha=0.5, **kwargs): ...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# 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"""