### Setup Plotnine Environment Source: https://plotnine.org/guide/scale-basics This snippet imports the necessary modules from the Plotnine library, including the main `plotnine` module and the `mpg` dataset, which is commonly used for examples and demonstrations. ```python from plotnine import * from plotnine.data import mpg ``` -------------------------------- ### Plotnine Example Setup and Theme Application Source: https://plotnine.org/reference/labs Initial setup for plotnine examples, including necessary imports for `ggplot`, `aes`, `labs`, `geom_point`, `theme`, `theme_538`, and `theme_set`. It also applies the `theme_538` to the plot for consistent styling. ```python from plotnine import ggplot, aes, labs, geom_point, theme, theme_538, theme_set from plotnine.data import mtcars theme_set(theme_538()) ``` -------------------------------- ### Install Plotnine for Local Development and Contribution Source: https://plotnine.org/guide/install Steps for setting up a local development environment for Plotnine, allowing users to clone the source code and install the package in editable mode for contributions. ```Bash $ git clone https://github.com/has2k1/plotnine.git $ cd plotnine $ pip install -e . ``` -------------------------------- ### Install Plotnine using various package managers Source: https://plotnine.org/guide/introduction Instructions for installing Plotnine using pip, uv, and conda package managers, including simple installs and installs with extra dependencies for examples. ```Shell # simple install pip install plotnine # with dependencies used in examples pip install 'plotnine[extra]' ``` ```Shell # simple install uv add plotnine # with dependencies used in examples uv add 'plotnine[extra]' ``` ```Shell # simple install conda install -c conda-forge plotnine # with dependencies used in examples conda install -c conda-forge 'plotnine[extra]' ``` -------------------------------- ### Install Plotnine Development Version Source: https://plotnine.org/guide/install Instructions for installing the latest, unreleased development version of Plotnine directly from its GitHub repository, useful for accessing recent bug fixes or new features. ```Bash # Using pip: $ pip install git+https://github.com/has2k1/plotnine.git # Using uv: $ uv pip install git+https://github.com/has2k1/plotnine.git ``` -------------------------------- ### Install Plotnine with Extra Packages Source: https://plotnine.org/guide/install Demonstrates how to install Plotnine along with recommended optional dependencies (adjustText, geopandas, scikit-learn, scikit-misc) for enhanced plotting and data handling capabilities. ```Bash # Using pip: $ pip install 'plotnine[extra]' # Using uv: $ uv pip install 'plotnine[extra]' # Using conda: $ conda install -c conda-forge 'plotnine[extra]' ``` -------------------------------- ### Plotnine geom_smooth Example Setup Source: https://plotnine.org/reference/geom_smooth Imports necessary modules from Plotnine and sets the Matplotlib theme for plotting examples. This code prepares the environment for demonstrating `geom_smooth` usage. ```python from plotnine import ggplot, aes, geom_point, geom_smooth, labs, theme_matplotlib, theme_set from plotnine.data import mpg theme_set(theme_matplotlib()) ``` -------------------------------- ### Setup Plotnine Environment Source: https://plotnine.org/guide/geometric-objects Imports necessary modules from plotnine, including the main plotnine library and the `mpg` dataset for examples. ```Python from plotnine import * from plotnine.data import mpg ``` -------------------------------- ### Install Plotnine Official Release Source: https://plotnine.org/guide/install Provides command-line instructions for installing the stable version of the Plotnine library using common Python package managers like pip, uv, and conda. ```Bash # Using pip: $ pip install plotnine # Using uv: $ uv pip install plotnine # Using conda: $ conda install -c conda-forge plotnine ``` -------------------------------- ### Setup Plotnine and Load Data Source: https://plotnine.org/guide/aesthetic-mappings Imports necessary modules from plotnine, including the main ggplot object and the penguins dataset for examples. ```python from plotnine import * from plotnine.data import penguins ``` -------------------------------- ### Create Data and Plot Base Density (plotnine) Source: https://plotnine.org/reference/examples/geom_density-preview Initial setup to create a DataFrame with numerical data and plot its density using `geom_density` in plotnine. This forms the foundation for subsequent highlighting techniques. ```python n = 101 df = pd.DataFrame({"x": np.arange(n)}) ( ggplot(df, aes("x")) + geom_density() ) ``` -------------------------------- ### Install Plotnine library Source: https://plotnine.org/guide/overview This command demonstrates how to install the Plotnine library using pip, the Python package installer. It is a prerequisite for using Plotnine's data visualization functionalities. ```bash pip install plotnine ``` -------------------------------- ### Setup Plotnine Environment Source: https://plotnine.org/guide/position-adjustments Imports necessary modules from plotnine, including the main library and the built-in diamonds dataset, to prepare the environment for plotting examples. ```python from plotnine import * from plotnine.data import diamonds ``` -------------------------------- ### PlotnineAnimation Example: Initial Imports and Matplotlib Setup Source: https://plotnine.org/reference/PlotnineAnimation This snippet imports necessary libraries like pandas, numpy, and plotnine components, including `PlotnineAnimation`. It also configures Matplotlib's animation backend for HTML5 rendering in notebooks. ```python import pandas as pd import numpy as np from plotnine import ggplot, aes, geom_path, theme, theme_void, lims from plotnine.animation import PlotnineAnimation # for animation in the notebook from matplotlib import rc rc("animation", html="html5") ``` -------------------------------- ### Customize Guides with guide_colorbar() and guide_legend() in Plotnine Source: https://plotnine.org/guide/scale-basics Customize guides by passing arguments like `guide_colorbar()` or `guide_legend()` to the `guides()` function. The example below uses `guide_colorbar()` to reverse the colorbar (in the legend on the right; note the styles are the same, but the way the guide colorbar is shown is reversed). ```python p = ( ggplot(mpg, aes("displ", "hwy", color="cyl")) + geom_point() + theme(legend_key_size=30) ) p p + guides(color=guide_colorbar(reverse=True)) ``` ```python import pandas as pd from plotnine import * ser = list(map(str, range(5))) df = pd.DataFrame({"x": ser, "y": ser, "p": ser, "q": ser, "r": ser}) ( ggplot(df, aes("x", "y", color="p", size="q", shape="r")) + geom_point() + labs(title="Merged color, size, and shape guides") + guides( color=guide_legend("THE GUIDE"), size=guide_legend("THE GUIDE"), shape=guide_legend("THE GUIDE"), ) ) ``` -------------------------------- ### plotnine.guides.guide.guide Class and Methods API Source: https://plotnine.org/reference/guide API documentation for the `guide` base class, including its constructor parameters and all associated methods. ```APIDOC Class: guide Signature: guide( title=None, theme=Theme(), position=None, direction=None, reverse=False, order=0 ) Description: Base class for all guides Parameters: title: Optional[str] = None Description: Title of the guide. Default is the name of the aesthetic or the name specified using `lab` theme: Theme = field(default_factory=Theme) Description: A theme to style the guide. If `None`, the plots theme is used. position: Optional[LegendPosition] = None Description: Where to place the guide relative to the panels. direction: Optional[Orientation] = None Description: Direction of the guide. The default is depends on `legend_position`. reverse: bool = False Description: Whether to reverse the order of the legend keys. order: int = 0 Description: Order of this guide among multiple guides. ``` ```APIDOC Method: create_geoms() Description: Create layers of geoms for the guide Returns: Optional[Self] Description: self if geom layers were create or None of no geom layers were created. ``` ```APIDOC Method: draw() Description: Draw guide ``` ```APIDOC Method: legend_aesthetics(layer) Description: Return the aesthetics that contribute to the legend Parameters: layer: Layer Description: Layer whose legend is to be drawn Returns: list Description: List of the names of the aethetics that contribute to the legend. ``` ```APIDOC Method: setup(guides) Description: Setup guide for drawing process ``` ```APIDOC Method: train(scale, aesthetic=None) Description: Create the key for the guide Returns: guide Description: Returns guide if training is successful ``` -------------------------------- ### Install ipyWidgets Source: https://plotnine.org/tutorials/miscellaneous-using-notebook-widgets Instructions to install `ipywidgets` using `pip` and enable the necessary extensions for Jupyter Notebooks and JupyterLab. JupyterLab requires `npm` for its manager. ```bash pip install ipywidgets # for jupyter notebooks: jupyter nbextension enable --py widgetsnbextension # for jupyter lab (requires npm): npm i @jupyter-widgets/jupyterlab-manager ``` -------------------------------- ### plotnine.layer.layer.setup Method API Source: https://plotnine.org/reference/layer API documentation for the `setup` method of the `layer` class, which prepares the layer for the plot building process. ```APIDOC setup() Prepare layer for the plot building ``` -------------------------------- ### Setup Plotnine Environment Source: https://plotnine.org/guide/coordinate-systems Imports the core Plotnine library and sample datasets (`diamonds`, `mpg`) for demonstration purposes. ```python from plotnine import * from plotnine.data import diamonds, mpg ``` -------------------------------- ### Python guides() Function Signature Source: https://plotnine.org/reference/guides The basic function signature for `plotnine.guides`, showing its available parameters and their default `None` values. ```python guides( alpha=None, color=None, fill=None, linetype=None, shape=None, size=None, stroke=None, colour=None ) ``` -------------------------------- ### Customize Legend Box Appearance in Plotnine Source: https://plotnine.org/gallery/theme Illustrates various theme options for customizing the legend box in Plotnine, including its position, direction, margins, background, key appearance, title, text, and spacing. The example uses `aes(fill="drat")` and `guides(color=guide_legend(ncol=2))` to set up a legend for demonstration purposes. ```python ( p1 + aes(fill="drat") + theme( legend_position="left", legend_direction="horizontal", # affected by the ncol=2 legend_box_margin=5, legend_background=element_rect(color=purple, size=2, fill="white"), legend_box="vertical", legend_key=element_rect(fill=gray, alpha=0.3), legend_title=element_text(color=orange, va="top"), legend_text=element_text(weight="bold"), legend_key_spacing=10, # overridden legend_key_spacing_x=15, legend_key_spacing_y=5 ) # so we can see legend_entry_spacing in action + guides(color=guide_legend(ncol=2)) ) ``` -------------------------------- ### Plotnine Python Environment and Module Imports Source: https://plotnine.org/reference/stage Initial setup for plotnine examples, including loading autoreload extensions and importing necessary modules like pandas, numpy, and specific components from plotnine such as `ggplot`, `aes`, `after_stat`, `stage`, `geom_bar`, `geom_text`, `geom_bin_2d`, and `stat_bin_2d`. ```python %load_ext autoreload %autoreload 2 %aimport plotnine import pandas as pd import numpy as np from plotnine import ( ggplot, aes, after_stat, stage, geom_bar, geom_text, geom_bin_2d, stat_bin_2d, ) ``` -------------------------------- ### Displaying Sample Data from mtcars Dataset Source: https://plotnine.org/reference/examples/theme-preview Shows the first few rows of the `mtcars` dataset, which will be used as the sample data for plotting demonstrations throughout the guide. ```python mtcars.head() ``` -------------------------------- ### Setup Plotnine Environment Source: https://plotnine.org/guide/annotations Imports the `plotnine` library and its `data` submodule, specifically loading the `penguins` dataset, to set up the environment for creating plots. ```python from plotnine import * from plotnine.data import penguins ``` -------------------------------- ### Setup Plotnine and Load Data Source: https://plotnine.org/guide/labels Initializes plotnine and loads the 'penguins' dataset, creating a base ggplot object for further modifications. ```python from plotnine import * from plotnine.data import penguins p = ( ggplot(penguins, aes("flipper_length_mm", "body_mass_g", color="species")) + geom_point() ) ``` -------------------------------- ### Importing Libraries for Plotnine Guitar Neck Example Source: https://plotnine.org/reference/scale_x_continuous Standard imports required for the plotnine examples, including numpy, pandas, and various plotnine components, along with mizani.transforms.trans for custom transformations. ```Python import numpy as np import pandas as pd from plotnine import ( ggplot, aes, geom_point, geom_path, scale_x_continuous, scale_y_continuous, guides, theme, element_line, element_rect, ) from mizani.transforms import trans ``` -------------------------------- ### Import plotnine modules for theme_bw example Source: https://plotnine.org/reference/theme_bw Imports necessary classes and functions from the plotnine library, including `ggplot`, `geom_point`, `aes`, `labs`, `theme_bw`, and `mtcars` dataset, to set up an example demonstrating the `theme_bw` functionality. ```python from plotnine import ggplot, geom_point, aes, labs, theme_bw from plotnine.data import mtcars ``` -------------------------------- ### Import Plotnine Libraries Source: https://plotnine.org/guide/themes-basics Imports necessary modules from the plotnine library, including the main `plotnine` module and the `penguins` dataset for examples. ```python from plotnine import * from plotnine.data import penguins ``` -------------------------------- ### Plotnine Basic `aes` Mapping Example Source: https://plotnine.org/reference/aes A fundamental example demonstrating how to map two DataFrame columns to the x and y aesthetics using `plotnine.aes` and visualize them with `geom_point`. ```python df = pd.DataFrame({ "col1": np.arange(11), "col2": np.arange(11) }) ( ggplot(df, aes(x="col1", y="col2")) + geom_point() ) ``` -------------------------------- ### Import Plotnine Modules and Data Source: https://plotnine.org/reference/examples/theme_classic-preview Imports essential classes and functions from the plotnine library, including `ggplot`, `aes`, `labs`, `theme_classic`, `geom_point`, and the `mtcars` dataset, which is commonly used for data visualization examples. ```python from plotnine import ggplot, aes, labs, theme_classic, geom_point from plotnine.data import mtcars ``` -------------------------------- ### Displaying Sample Data Head Source: https://plotnine.org/gallery/geom_density Shows the first few rows of the 'mpg' dataset, which is used throughout the examples for plotting. ```python mpg.head() ``` -------------------------------- ### Preview mpg Dataset for Plotnine Examples Source: https://plotnine.org/reference/geom_bar Displays the first few rows of the `mpg` dataset, providing an overview of the data structure and columns used in Plotnine examples, such as 'manufacturer', 'model', and 'class'. ```python mpg.head() ``` -------------------------------- ### Plotnine Scale Expansion Parameter Examples Source: https://plotnine.org/reference/scale_fill_gray Illustrative examples for configuring the `expand` parameter in plotnine scales, showing how different tuple values affect the expansion of plot limits. ```python (0, 0) # Do not expand. (0, 1) # Expand lower and upper limits by 1 unit. (1, 0) # Expand lower and upper limits by 100%. (0, 0, 0, 0) # Do not expand, as (0, 0). (0, 0, 0, 1) # Expand upper limit by 1 unit. (0, 1, 0.1, 0) # Expand lower limit by 1 unit and upper limit by 10%. (0, 0, 0.1, 2) # Expand upper limit by 10% plus 2 units. ``` -------------------------------- ### Importing Plotnine Modules for geom_abline Example Source: https://plotnine.org/reference/geom_abline Imports necessary modules from the Plotnine library and pandas data for demonstrating the `geom_abline` function. ```python from plotnine import ggplot, aes, geom_point, labs, geom_abline, facet_grid from plotnine.data import mpg ``` -------------------------------- ### Create Plotnine Scatter Plot with Custom Labels and Theme Adjustments Source: https://plotnine.org/gallery/labs This example constructs a scatter plot visualizing the relationship between vehicle weight and fuel efficiency from the `mtcars` dataset. It showcases advanced customization including mapping aesthetics to data, adding comprehensive labels (title, subtitle, axes, legend), and fine-tuning the plot caption's alignment and spacing using `element_text`. ```Python caption = """\ This graphic illustrates the inverse relationship between vehicle weight and fuel efficiency (MPG). It aims to highlight how heavier vehicles generally consume more fuel, and how the complexity of an engine's cylinder count and transmission system can affect its fuel economy. """ from plotnine import * ( ggplot(mtcars, aes("mpg", "wt", colour="factor(cyl)", size="gear")) + geom_point() + labs( x="Miles per Gallon", y="Weight", colour="Cylinders", size="Gears", title="Fuel Efficiency vs. Vehicle Weight", subtitle ="Exploring Factors that Affect the Fuel Effeciency of a Car", caption=caption, ) + theme( # left justify the caption and have one line of space between it and # the x-axis label plot_caption=element_text(ha="left", margin={"t": 1, "units": "lines"}) ) ) ``` -------------------------------- ### Plotnine Scale Expansion Examples Source: https://plotnine.org/reference/scale_size_identity Illustrates various configurations for the `expand` parameter in Plotnine scales, showing how multiplicative and additive constants affect scale expansion. Examples include no expansion, fixed unit expansion, percentage expansion, and mixed expansions. ```python (mul, add) (mul_low, add_low, mul_high, add_high) (0, 0) - Do not expand. (0, 1) - Expand lower and upper limits by 1 unit. (1, 0) - Expand lower and upper limits by 100%. (0, 0, 0, 0) - Do not expand, as (0, 0). (0, 0, 0, 1) - Expand upper limit by 1 unit. (0, 1, 0.1, 0) - Expand lower limit by 1 unit and upper limit by 10%. (0, 0, 0.1, 2) - Expand upper limit by 10% plus 2 units. ``` -------------------------------- ### Control Legend Merging in Plotnine Source: https://plotnine.org/guide/scale-basics Sometimes aesthetics mapped to the same variable have their guides merged, for example, color and shape might be shown on the same guide. To split a merged guide, give the scales their own names. ```python p = ( ggplot(mpg, aes("displ", "hwy", color="factor(cyl)", shape="factor(cyl)")) + geom_point() + theme_grey(base_size=20) ) p + labs(title="Unmerged") p + labs(title="Merged") + scale_shape_discrete(name="Shape") ``` -------------------------------- ### plotnine.scale_shape_manual API Parameters Source: https://plotnine.org/reference/scale_shape_manual Detailed API documentation for the parameters of the `scale_shape_manual` function, including types, descriptions, and usage examples for complex parameters like 'expand'. ```APIDOC Init Parameters: values: Sequence[Any] | dict[Any, Any] Shapes that make up the palette. See matplotlib.markers for list of all possible shapes. The values will be matched with the limits of the scale or the breaks if provided. If it is a dict then it should map data values to shapes. Parameter Attributes: name: str | None = None The name of the scale. It is used as the label of the axis or the title of the guide. Suitable defaults are chosen depending on the type of scale. breaks: DiscreteBreaksUser = True List of major break points. Or a callable that takes a tuple of limits and returns a list of breaks. If True, automatically calculate the breaks. limits: DiscreteLimitsUser = None Limits of the scale. These are the categories (unique values) of the variables. If is only a subset of the values, those that are left out will be treated as missing data and represented with a na_value. labels: ScaleLabelsUser = True Labels at the breaks. Alternatively, a callable that takes an array_like of break points as input and returns a list of strings. expand: (tuple[float, float] | tuple[float, float, float, float] | None) = None Multiplicative and additive expansion constants that determine how the scale is expanded. If specified must be of length 2 or 4. Specifically the values are in this order: (mul, add) (mul_low, add_low, mul_high, add_high) For example, * (0, 0) - Do not expand. * (0, 1) - Expand lower and upper limits by 1 unit. * (1, 0) - Expand lower and upper limits by 100%. * (0, 0, 0, 0) - Do not expand, as (0, 0). * (0, 0, 0, 1) - Expand upper limit by 1 unit. * (0, 1, 0.1, 0) - Expand lower limit by 1 unit and upper limit by 10%. * (0, 0, 0.1, 2) - Expand upper limit by 10% plus 2 units. If not specified, suitable defaults are chosen. guide: Literal["legend"] | None = "legend" na_value: Any = np.nan If na_translate=True, what aesthetic value should be assigned to the missing values. This parameter does not apply to position scales where nan is always placed on the right. aesthetics: Sequence[ScaledAestheticsName] = () Aesthetics affected by this scale. These are defined by each scale and the user should probably not change them. Have fun. drop: bool = True Whether to drop unused categories from the scale na_translate: bool = True If True translate missing values and show them. If False remove missing values. ``` -------------------------------- ### Previewing MPG Dataset with Pandas Source: https://plotnine.org/reference/geom_density Shows the first few rows of the `mpg` dataset, which is used as example data for plotnine demonstrations. ```python mpg.head() ``` -------------------------------- ### plotnine.guides API Reference Source: https://plotnine.org/reference/guides Comprehensive API documentation for the `plotnine.guides` function, detailing its purpose and all available parameters with their types and descriptions. ```APIDOC plotnine.guides function: Description: Guides for each scale. Used to assign or remove a particular guide to the scale of an aesthetic. Signature: guides(alpha=None, color=None, fill=None, linetype=None, shape=None, size=None, stroke=None, colour=None) Parameters: alpha: Optional[LegendOrColorbar | NoGuide] = None Guide for alpha scale. color: Optional[LegendOrColorbar | NoGuide] = None Guide for color scale. fill: Optional[LegendOrColorbar | NoGuide] = None Guide for fill scale. linetype: Optional[LegendOnly | NoGuide] = None Guide for linetype scale. shape: Optional[LegendOnly | NoGuide] = None Guide for shape scale. size: Optional[LegendOnly | NoGuide] = None Guide for size scale. stroke: Optional[LegendOnly | NoGuide] = None Guide for stroke scale. colour: Optional[LegendOnly | NoGuide] = None Guide for colour scale. ``` -------------------------------- ### Plotnine: Initial Setup and Theme Configuration Source: https://plotnine.org/gallery/geom_smooth Imports necessary plotnine modules and sets the matplotlib theme for consistent plotting style across examples. ```python from plotnine import ggplot, aes, geom_point, geom_smooth, labs, theme_matplotlib, theme_set from plotnine.data import mpg theme_set(theme_matplotlib()) ``` -------------------------------- ### Render Unthemed Plot p2 Source: https://plotnine.org/reference/examples/theme-preview Displays the `p2` plot object, which includes faceting, to show its default, unthemed appearance. This provides another baseline for themed examples. ```python p2 ``` -------------------------------- ### Add Single Vertical Line to Scatter Plot Source: https://plotnine.org/reference/examples/geom_vline-preview This example demonstrates how to add a single vertical line to an existing scatter plot using `geom_vline()`. The line is placed at `xintercept=5` to serve as a visual guide. ```python ( ggplot(mpg, aes(x="displ", y="hwy")) + geom_point() + geom_vline(xintercept=5) # add one vertical line + labs(x="displacement", y="horsepower") ) ``` -------------------------------- ### Setup Plotnine for Theme Demonstration Source: https://plotnine.org/guide/themes-premade Initializes a `plotnine` ggplot object `p` using the `penguins` dataset. It sets up aesthetic mappings for flipper length and body mass, adds point geometry, customizes x-axis breaks, facets the plot by species, and includes a subtitle. This base plot `p` is then used to demonstrate the application of various premade themes. ```python from plotnine import * from plotnine.data import penguins p = ( ggplot(penguins, aes(x="flipper_length_mm", y="body_mass_g", color="species")) + geom_point() + scale_x_continuous(breaks=range(150, 250, 30)) + facet_wrap("~species") + labs(subtitle="I am a subtitle") ) ``` -------------------------------- ### Import Plotnine Modules and Data Source: https://plotnine.org/gallery/geom_abline Imports essential components from the plotnine library, including `ggplot`, `aes`, `geom_point`, `labs`, `geom_abline`, and `facet_grid`. It also imports the `mpg` dataset, which is used for all plotting examples throughout the guide. ```python from plotnine import ggplot, aes, geom_point, labs, geom_abline, facet_grid from plotnine.data import mpg ``` -------------------------------- ### plotnine.guide_colorbar API Reference Source: https://plotnine.org/reference/guide_colorbar Detailed API documentation for the guide_colorbar function in plotnine, including its signature, all configurable parameters with their types and descriptions, and important usage notes. ```APIDOC guide_colorbar( title=None, theme=Theme(), position=None, direction=None, reverse=False, order=0, nbin=None, display="gradient", alpha=None, draw_ulim=True, draw_llim=True ) Description: Guide colorbar Parameters: title: Optional[str] = None Title of the guide. Default is the name of the aesthetic or the name specified using `lab` theme: Theme = field(default_factory=Theme) A theme to style the guide. If `None`, the plots theme is used. position: Optional[LegendPosition] = None Where to place the guide relative to the panels. direction: Optional[Orientation] = None Direction of the guide. The default is depends on `legend_position`. reverse: bool = False Whether to reverse the order of the legend keys. order: int = 0 Order of this guide among multiple guides. nbin: Optional[int] = None Number of bins for drawing a colorbar. A larger value yields a smoother colorbar display: Literal["gradient", "rectangles", "raster"] = "gradient" How to render the colorbar. alpha: Optional[float] = None Opacity (in the range `[0, 1]`) of the colorbar. The default `None`, is to use the opacity of the plot. draw_ulim: bool = True Whether to show the upper limit tick marks. draw_llim: bool = True Whether to show the lower limit tick marks. Notes: To correctly place a rasterized colorbar when saving the plot as an `svg` or `pdf`, you should set the `dpi` to 72 i.e. `theme(dpi=72)`. ``` -------------------------------- ### plotnine.layer.layer.setup_data Method API Source: https://plotnine.org/reference/layer API documentation for the `setup_data` method of the `layer` class, which prepares or modifies data for plotting. ```APIDOC setup_data() Prepare/modify data for plotting ``` -------------------------------- ### Apply Position Scale Transformations (Reverse, Log10) in Plotnine Source: https://plotnine.org/guide/scale-basics This example demonstrates applying transformations to position scales (x and y axes) in Plotnine. It uses `scale_x_reverse()` to reverse the x-axis and `scale_y_log10()` to apply a base-10 logarithmic transformation to the y-axis. ```python (ggplot(mpg, aes("displ", "hwy")) + geom_point() + scale_x_reverse() + scale_y_log10()) ``` -------------------------------- ### Customize Break Labels with labels= in Plotnine Source: https://plotnine.org/guide/scale-basics Use the `labels=` argument to set custom labels for breaks. This argument supports either a function that operates on a list of breaks, or a list of labels. For example, the plot below sets the color labels to uppercase. ```python p = ggplot(mpg, aes("displ", "hwy", color="class")) + geom_point() p + scale_color_discrete(labels=lambda breaks: [s.upper() for s in breaks]) ``` ```python p + scale_x_continuous(breaks = [2, 4, 6], labels = ["TWO", "FOUR", "SIX"]) ``` -------------------------------- ### Set Manual Styles with values= in Plotnine Source: https://plotnine.org/guide/scale-basics Use the `values=` argument to manually specify stylings like colors, shapes, or sizes of the scale. For example, the plot below manually sets point shapes (see the aesthetic specification for shape value options). ```python keep_classes = ["2seater", "compact", "midsize"] ( mpg[mpg["class"].isin(keep_classes)] >> ggplot(aes("displ", "hwy", shape="factor(cyl)")) + geom_point() + scale_shape_manual(values=[".", "o", "v", ">"]) ) ``` -------------------------------- ### Plotnine Basic Setup and Theme Configuration Source: https://plotnine.org/reference/scale_fill_continuous This snippet demonstrates how to import necessary modules from Plotnine, including core components, geoms, scales, and coordinate systems. It also shows how to load sample data and set a default theme for all plots using `theme_set`. ```python from plotnine import ( ggplot, aes, theme_matplotlib, theme_set, geom_tile, scale_fill_continuous, coord_cartesian ) from plotnine.data import faithfuld # Set default theme for all the plots theme_set(theme_matplotlib()) ``` -------------------------------- ### Initialize Plotnine and Data Libraries Source: https://plotnine.org/reference/examples/stage-preview Loads the autoreload extension and imports essential modules from `plotnine`, `pandas`, and `numpy` to prepare the environment for data manipulation and statistical plotting. ```Python %load_ext autoreload %autoreload 2 %aimport plotnine import pandas as pd import numpy as np from plotnine import ( ggplot, aes, after_stat, stage, geom_bar, geom_text, geom_bin_2d, stat_bin_2d, ) ``` -------------------------------- ### Define Base Plotnine Plots and Color Palette Source: https://plotnine.org/reference/examples/theme-preview Creates two base `ggplot` objects, `p1` and `p2` (with `facet_grid`), which serve as the foundation for applying various theme modifications. Also defines a set of color variables for consistent use in theming examples. ```python p1 = ( ggplot(mtcars, aes("wt", "mpg", color="factor(cyl)")) + geom_point() + labs(title="mpg vs wt") ) p2 = p1 + facet_grid("gear", "am") black = "#222222" gray = "#666666" red = "#FF3333" green = "#66CC00" blue = "#3333FF" purple = "#9933FF" orange = "#FF8000" yellow = "#FFFF33" ``` -------------------------------- ### Plotnine v0.14 Core Imports and Theme Setup Source: https://plotnine.org/blog/2024/11/version-0.14.0/index This snippet demonstrates the essential Python imports required to start using plotnine v0.14, including pandas for data handling and various plotnine components like ggplot, geom_point, and theme utilities. It also sets the default theme to theme_matplotlib. ```Python import pandas as pd from plotnine import ( aes, ggplot, geom_point, geom_text, scale_x_datetime, theme, theme_set, theme_matplotlib, ) theme_set(theme_matplotlib()); ``` -------------------------------- ### Custom geom_density_highlight Class and Usage in Plotnine Source: https://plotnine.org/reference/examples/geom_density-preview Defines a custom `geom_density_highlight` class that extends `geom_density` to filter and highlight a specific region of a density plot. The `setup_data` method applies a query to the data based on the `region` attribute. The accompanying example demonstrates how to instantiate and use this custom geom within a `ggplot` object, combining it with standard `geom_density` and `annotate` to visually emphasize a defined data range. ```python class geom_density_highlight(geom_density): def __init__(self, *args, region=(-np.inf, np.inf), **kwargs): super().__init__(*args, **kwargs) self.region = region def setup_data(self, data): data = super().setup_data(data) s = f"{self.region[0]} <= x <= {self.region[1]}" data = data.query(s).reset_index(drop=True) return data region = (40, 60) teal = "#029386" ( ggplot(df, aes("x")) + geom_density_highlight(region=region, fill=teal + "88", color="none") + geom_density(fill=teal + "44", color=teal, size=0.7) + annotate(geom_vline, xintercept=region, color=teal, size=0.7) + theme_tufte() ) ``` -------------------------------- ### Plotnine Scale Parameter: guide Source: https://plotnine.org/reference/scale_alpha_datetime Specifies the type of guide for the scale, defaulting to 'legend'. ```APIDOC guide: Literal["legend"] = "legend" ``` -------------------------------- ### Setup Plotnine Environment Source: https://plotnine.org/guide/facets Imports necessary modules from plotnine for data visualization, including the core ggplot object and sample datasets like mpg and penguins, preparing the environment for plotting. ```python from plotnine import * from plotnine.data import mpg, penguins ``` -------------------------------- ### Set Guide Labels Using `name` Argument in Plotnine Scales Source: https://plotnine.org/guide/scale-basics This code demonstrates how to explicitly set the labels for plot guides (x-axis, y-axis, and color legend) using the `name=` argument within individual scale functions like `scale_x_continuous()`, `scale_y_continuous()`, and `scale_color_discrete()`. ```python ( ggplot(mpg, aes("displ", "hwy", color="class")) + geom_point() + scale_x_continuous(name="Engine displacement (litres)") + scale_y_continuous(name="Highway miles per gallon") + scale_color_discrete(name="Car class") ) ``` -------------------------------- ### Position Multiple Plotnine Guides Independently Source: https://plotnine.org/changelog This Python snippet demonstrates how to place multiple guides (e.g., colorbar, fill legend, size legend) at different positions around the plot panels using the `guides()` function. It allows for flexible arrangement of legends and colorbars within the plot layout. ```Python + guides( color=guide_colorbar(position="left"), fill=guide_legend(position="bottom"), size=guide_legend(position="bottom") ) ``` -------------------------------- ### Sample Data Structure from geom_density_highlight.setup_data Source: https://plotnine.org/reference/geom_density This output displays a sample of the DataFrame structure passed to `setup_data` within the `geom_density_highlight` class. It shows columns like `x`, `y`, `density`, `count`, `ymin`, and `ymax`, which are crucial for understanding how to filter the data to highlight a specific region. This output informs the next step of filtering based on the `x` column. ```Text PANEL count density group n scaled x y \ 0 1 0.519038 0.005139 -1 101 0.519039 0.000000 0.005139 1 1 0.522757 0.005176 -1 101 0.522758 0.097752 0.005176 2 1 0.526473 0.005213 -1 101 0.526474 0.195503 0.005213 3 1 0.530187 0.005249 -1 101 0.530188 0.293255 0.005249 4 1 0.533899 0.005286 -1 101 0.533900 0.391007 0.005286 ... 1019 1 0.533899 0.005286 -1 101 0.533900 99.608993 0.005286 1020 1 0.530187 0.005249 -1 101 0.530188 99.706745 0.005249 1021 1 0.526473 0.005213 -1 101 0.526474 99.804497 0.005213 1022 1 0.522757 0.005176 -1 101 0.522758 99.902248 0.005176 1023 1 0.519038 0.005139 -1 101 0.519039 100.000000 0.005139 ymin ymax 0 0 0.005139 1 0 0.005176 2 0 0.005213 3 0 0.005249 4 0 0.005286 ... 1019 0 0.005286 1020 0 0.5249 1021 0 0.5213 1022 0 0.5176 1023 0 0.5139 [1024 rows x 10 columns] ``` -------------------------------- ### Plotnine v0.5.0: geopandas No Longer a Core Requirement Source: https://plotnine.org/changelog `geopandas` has been removed as a core installation requirement. Users of `geom_map` must now install it separately. ```APIDOC Dependency: - geopandas: Removed as core requirement. - plotnine.geom_map: Users must install geopandas separately. ``` -------------------------------- ### Import Plotnine and Load Data Source: https://plotnine.org/reference/examples/facet_grid-preview Imports necessary components from plotnine, including `ggplot`, `aes`, `geom_point`, `labs`, `facet_grid`, `theme`, `element_text`, and `element_rect`, along with the `mpg` dataset for examples. ```python from plotnine import ggplot, aes, geom_point, labs, facet_grid, theme, element_text, element_rect from plotnine.data import mpg ``` -------------------------------- ### Plotnine Example Imports Source: https://plotnine.org/reference/after_stat Standard imports required for running plotnine examples, including pandas for data manipulation and numpy for numerical operations. ```Python import pandas as pd import numpy as np from plotnine import ggplot, aes, after_stat, geom_bar, labs ``` -------------------------------- ### plotnine.themes.themeable.panel_ontop API Reference Source: https://plotnine.org/reference/panel_ontop Detailed API documentation for the `panel_ontop` theme element, explaining its purpose and the `theme_element` parameter. ```APIDOC Function: panel_ontop Description: Place panel background & gridlines over/under the data layers Parameters: theme_element: Type: bool Description: Default is False. ``` -------------------------------- ### plotnine.scale_fill_cmap Init Parameters Source: https://plotnine.org/reference/scale_fill_cmap Detailed documentation for the initialization parameters of the `plotnine.scale_fill_cmap` function, including types, default values, and descriptions for each parameter. ```APIDOC scale_fill_cmap Parameters: cmap_name: type: str default: 'viridis' description: A standard Matplotlib colormap name. The default is 'viridis'. For the list of names checkout the output of `matplotlib.cm.cmap_d.keys()` or see [colormaps](https://matplotlib.org/stable/users/explain/colors/colormaps.html). ``` -------------------------------- ### Rename Legends with guides and guide_legend Source: https://plotnine.org/reference/scale_color_discrete Illustrates another approach to customize legend titles by using the guides function in conjunction with guide_legend for both 'fill' and 'color' aesthetics. ```python ( ggplot(df) + geom_col(aes("x", "y", fill="cat")) + geom_point(aes("x", y="yfit", color="cat")) + geom_path(aes("x", y="yfit", color="cat")) + scale_color_discrete(l=0.4) + guides( # new fill=guide_legend(title="Data"), color=guide_legend(title="Model") ) ) ``` -------------------------------- ### Set Global Plotnine Theme Source: https://plotnine.org/gallery/labs This snippet demonstrates how to apply a global theme to all subsequent plotnine visualizations. It imports necessary components and uses `theme_set` to apply the `theme_538` style, providing a consistent aesthetic across plots. ```Python from plotnine import ggplot, aes, labs, geom_point, theme, theme_538, theme_set from plotnine.data import mtcars theme_set(theme_538()) ``` -------------------------------- ### Subclass Premade Plotnine Themes for Customization Source: https://plotnine.org/guide/themes-basics Demonstrates how to create a custom theme by subclassing an existing premade theme (e.g., `theme_gray`) and adding specific customizations, such as rotating and coloring x-axis text, while retaining the base theme's properties. ```Python class custom_theme(theme_gray): def __init__(self, base_size=11, base_family=None): super().__init__(base_size=base_size, base_family=base_family) self += theme(axis_text_x=element_text(angle=90, color="purple")) p = ggplot(penguins, aes(x="flipper_length_mm", y="body_mass_g")) + geom_point() p + custom_theme() p + custom_theme(base_size=24) ``` -------------------------------- ### Pandas Series String Concatenation Example Source: https://plotnine.org/reference/after_scale A small example showing how string concatenation works with pandas Series, which is the underlying mechanism for modifying color strings in `after_scale`. ```python pd.Series(['#AABBCC', '#112233']) + '66' == pd.Series(['#AABBCC66', '#11223366']) ``` -------------------------------- ### Plotnine Coordinate System: setup_params Method Source: https://plotnine.org/reference/coord This method is designed to create additional parameters for a coordinate system, leveraging the original data provided to the layers. It's essential for initializing the coordinate system's state based on the input data before any further manipulations occur. ```APIDOC setup_params(data) Parameters: data: list[pd.DataFrame] Data for each layer before it is manipulated in any way. ``` -------------------------------- ### Plotnine Scale Guides API Reference Source: https://plotnine.org/reference/index API reference for classes and functions related to guides (axes, legends, colorbars) that help interpret data represented on scales in Plotnine. ```APIDOC guide: Base class for all guides ``` ```APIDOC guides: Guides for each scale ``` ```APIDOC guide_legend: Legend guide ``` ```APIDOC guide_colorbar: Guide colorbar ``` -------------------------------- ### Plotnine Themeable Class API Reference Source: https://plotnine.org/reference/themeable Comprehensive API documentation for the `plotnine.themes.themeable.themeable` abstract class, including its constructor, attributes (`properties`, `rcParams`), and methods (`apply`, `apply_ax`, `apply_figure`, `blank_ax`, `blank_figure`, `from_class_name`, `is_blank`, `merge`). It details their purpose, parameters, return types, and usage notes. ```APIDOC Class: themeable Constructor: themeable(theme_element) Description: Abstract class of things that can be themed. Every subclass of themeable is stored in a dict at `register` with the name of the subclass as the key. It is the base of a class hierarchy that uses inheritance in a non-traditional manner. In the textbook use of class inheritance, superclasses are general and subclasses are specializations. In some since the hierarchy used here is the opposite in that superclasses are more specific than subclasses. It is probably better to think if this hierarchy of leveraging Python’s multiple inheritance to implement composition. For example the `axis_title` themeable is *composed of* the `x_axis_title` and the `y_axis_title`. We are just using multiple inheritance to specify this composition. When implementing a new themeable based on the ggplot2 documentation, it is important to keep this in mind and reverse the order of the “inherits from” in the documentation. If the superclasses fully implement the subclass, the body of the subclass should be “pass”. Python(mro) will do the right thing. When a method does require implementation, call `super()` then add the themeable’s implementation to the axes. Notes: A user should never create instances of class `Themeable` or subclasses of it. Attributes: properties: Description: Return only the properties that can be applied rcParams: Type: dict[str, Any] Description: Return themeables rcparams to an rcparam dict before plotting. Returns: dict: Dictionary of legal matplotlib parameters. Notes: This method should always call super(…).rcParams and update the dictionary that it returns with its own value, and return that dictionary. This method is called before plotting. It tends to be more useful for general themeables. Very specific themeables often cannot be be themed until they are created as a result of the plotting process. Methods: apply(theme): Description: Called by the theme to apply the themeable. Subclasses should not have to override this method apply_ax: Description: Called after a chart has been plotted. apply_figure: Description: Apply theme to the figure blank_ax: Description: Blank out theme elements blank_figure: Description: Blank out elements on the figure from_class_name: Description: Create a themeable by name is_blank: Description: Return True if theme_element is made of element_blank merge: Description: Merge properties of other into self ``` -------------------------------- ### Plotnine: Separate Guides for Shared Scales with Different Mappings Source: https://plotnine.org/changelog Aesthetics sharing a scale (e.g., color and fill) now receive different guides if they are mapped to different columns, enhancing clarity. ```APIDOC Plotting System: Scales: - Shared Scales (e.g., color, fill): - Guides: Separate if mapped to different columns. ``` -------------------------------- ### API Documentation for plotnine.scale_color_desaturate Init Parameters Source: https://plotnine.org/reference/scale_color_desaturate Detailed documentation for the initialization parameters of the `plotnine.scale_color_desaturate` function, including their types, default values, and descriptions. ```APIDOC color: str = 'red' Color to desaturate prop: float = 0 Saturation channel of color will be multiplied by this value. reverse: bool = False Whether to go from color to desaturated color or desaturated color to color. ``` -------------------------------- ### Plotnine Example Imports Source: https://plotnine.org/reference/scale_shape_identity This snippet provides the necessary import statements for common plotnine components, including geoms, scales, themes, and utility libraries like polars and numpy, used in examples. ```python from plotnine import ( aes, annotate, coord_equal, element_rect, element_text, facet_wrap, geom_point, geom_segment, geom_text, geom_tile, ggplot, lims, scale_shape_identity, theme, theme_void, ) import polars as pl import numpy as np ```