### Install Plotnine with pip, uv, or conda Source: https://plotnine.org/reference/guide/introduction These snippets provide commands to install the Plotnine library. Users can choose between pip, uv, or conda for installation. The 'extra' option includes additional dependencies used in examples. ```Bash # simple install pip install plotnine # with dependencies used in examples pip install 'plotnine[extra]' ``` ```Bash # simple install uv add plotnine # with dependencies used in examples uv add 'plotnine[extra]' ``` ```Bash # simple install conda install -c conda-forge plotnine # with dependencies used in examples conda install -c conda-forge 'plotnine[extra]' ``` -------------------------------- ### Create Artistic Plots with Plotnine, Polars, and Mizani Source: https://plotnine.org/reference/guide/introduction Shows an advanced example of creating artistic plots with Plotnine, involving data manipulation with Polars for generating random data and custom color palettes from Mizani, demonstrating complex data visualization techniques like area plots with unique styling. ```python import polars as pl import numpy as np from plotnine import * from mizani.palettes import brewer_pal, gradient_n_pal np.random.seed(345678) # generate random areas for each group to fill per year --------- # Note that in the data the x-axis is called Year, and the # filled bands are called Group(s) opts = [0] * 100 + list(range(1, 31)) values = [] for ii in range(30): values.extend(np.random.choice(opts, 30, replace=False)) # Put all the data together ------------------------------------- years = pl.DataFrame({"Year": list(range(30))}) groups = pl.DataFrame({"Group": [f"grp_{ii}" for ii in range(30)]}) df = ( years.join(groups, how="cross") .with_columns(Values=pl.Series(values)) .with_columns(prop=pl.col("Values") / pl.col("Values").sum().over("Year")) ) df.write_csv("plot-data.csv") # Generate color palette ---------------------------------------- # this uses 12 colors interpolated to all 30 Groups pal = brewer_pal("qual", "Paired") colors = pal(12) np.random.shuffle(colors) all_colors = gradient_n_pal(colors)(np.linspace(0, 1, 30)) # Plot --------------------------------------------------------- ( df >> ggplot(aes("Year", "prop", fill="Group")) + geom_area() + scale_fill_manual(values=all_colors) + theme( axis_text=element_blank(), line=element_blank(), title=element_blank(), legend_position="none", plot_margin=0, panel_border=element_blank(), panel_background=element_blank() ) ) ``` -------------------------------- ### plotnine.guides.guide.guide Class API Source: https://plotnine.org/reference/reference/guide API documentation for the `guide` base class, including its constructor parameters and methods for guide creation, drawing, and setup. ```APIDOC guide( title=None, theme=Theme(), position=None, direction=None, reverse=False, order=0 ) Base class for all guides 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. Notes: At the moment not all parameters have been fully implemented. Methods: create_geoms() Create layers of geoms for the guide Returns: Optional[Self] self if geom layers were create or None of no geom layers were created. draw() Draw guide legend_aesthetics(layer) Return the aesthetics that contribute to the legend Parameters: layer: Layer Layer whose legend is to be drawn Returns: list List of the names of the aethetics that contribute to the legend. setup(guides) Setup guide for drawing process train(scale, aesthetic=None) Create the key for the guide Returns: Returns guide if training is successful ``` -------------------------------- ### Setup Plotnine for Theming Examples Source: https://plotnine.org/reference/guide/themes-basics Imports necessary modules from plotnine, including the main library and the 'penguins' dataset, which will be used for demonstration plots. ```python from plotnine import * from plotnine.data import penguins ``` -------------------------------- ### Install Plotnine for Source Code Contribution Source: https://plotnine.org/reference/guide/install Steps to clone the Plotnine source repository and install it in development mode. This setup allows users to contribute to the project's source code by making changes directly to the cloned repository. ```bash $ git clone https://github.com/has2k1/plotnine.git $ cd plotnine $ pip install -e . ``` -------------------------------- ### Setup Plotnine Environment Source: https://plotnine.org/reference/guide/annotations Imports necessary libraries from plotnine for data visualization and loads the penguins dataset, preparing the environment for plotting examples. ```python from plotnine import * from plotnine.data import penguins ``` -------------------------------- ### Plotnine Example Setup Source: https://plotnine.org/reference/reference/labs This snippet imports necessary modules from plotnine, including `ggplot`, `aes`, `labs`, `geom_point`, `theme`, `theme_538`, and `theme_set`. It also imports the `mtcars` dataset and sets the default plot theme to `theme_538` for consistent styling in subsequent examples. ```python from plotnine import ggplot, aes, labs, geom_point, theme, theme_538, theme_set from plotnine.data import mtcars theme_set(theme_538()) ``` -------------------------------- ### Create Publication-Ready Plots with Plotnine Source: https://plotnine.org/reference/guide/introduction Demonstrates how to create publication-ready plots using Plotnine, including custom themes, axis adjustments, facetting, and specific coordinate settings for precise visualization. ```python from plotnine import * from plotnine.data import anscombe_quartet ( ggplot(anscombe_quartet, aes("x", "y")) + geom_point(color="sienna", fill="orange", size=3) + geom_smooth(method="lm", se=False, fullrange=True, color="steelblue", size=1) + facet_wrap("dataset") + labs(title="Anscombe’s Quartet") + scale_y_continuous(breaks=(4, 8, 12)) + coord_fixed(xlim=(3, 22), ylim=(2, 14)) + theme_tufte(base_family="Futura", base_size=16) + theme( axis_line=element_line(color="#4d4d4d"), axis_ticks_major=element_line(color="#00000000"), axis_title=element_blank(), panel_spacing=0.09 ) ) ``` -------------------------------- ### Install Plotnine Official Release Source: https://plotnine.org/reference/guide/install Instructions to install the official release of Plotnine using pip, uv, or conda. This is the recommended method for most users to get the stable version of the library. ```bash # Using pip: $ pip install plotnine # Using uv: $ uv pip install plotnine # Using conda: $ conda install -c conda-forge plotnine ``` -------------------------------- ### Setup Plotnine Environment Source: https://plotnine.org/reference/guide/geometric-objects Imports necessary modules from plotnine for data visualization and loads the example 'mpg' dataset, preparing the environment for plotting. ```python from plotnine import * from plotnine.data import mpg ``` -------------------------------- ### Setup Plotnine for Coordinate System Examples Source: https://plotnine.org/reference/guide/coordinate-systems This snippet imports the necessary `plotnine` library and sample datasets (`diamonds`, `mpg`) required for demonstrating various coordinate system functionalities. ```python from plotnine import * from plotnine.data import diamonds, mpg ``` -------------------------------- ### Import Plotnine and Sample Data Source: https://plotnine.org/reference/guide/scale-basics This snippet demonstrates how to import the core `plotnine` library and the `mpg` dataset, which is commonly used for examples in Plotnine documentation. ```python from plotnine import * from plotnine.data import mpg ``` -------------------------------- ### Setup Plotnine Environment Source: https://plotnine.org/reference/guide/aesthetic-mappings Imports necessary modules from plotnine for data visualization, including ggplot and aes, and loads the penguins dataset for examples. ```python from plotnine import * from plotnine.data import penguins ``` -------------------------------- ### Example Output Data from Plotnine Density Setup Source: https://plotnine.org/reference/reference/geom_density This snippet shows a sample of the DataFrame output from the `setup_data` method of `geom_density_highlight`. It illustrates the structure and content of the data processed by Plotnine's density calculation, including columns like `count`, `density`, `x`, `y`, `ymin`, and `ymax`. This output helps in understanding the data transformation before plotting. ```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.005249 1021 0 0.005213 1022 0 0.005176 1023 0 0.005139 [1024 rows x 10 columns] ``` -------------------------------- ### Plotnine Theme API: setup Method Source: https://plotnine.org/reference/reference/theme The `setup` method prepares the theme for application. It is called after the figure and axes are created but before plotting. This method provides references to the figure/axes and initializes storage for themed artists. ```APIDOC setup(plot) Setup theme for applying This method will be called when the figure and axes have been created but before any plotting or other artists have been added to the figure. This method gives the theme and the elements references to the figure and/or axes. It also initialises where the artists to be themed will be stored. ``` -------------------------------- ### Generate Geospatial Plots with Plotnine and GeoPandas Source: https://plotnine.org/reference/guide/introduction Illustrates how to create geospatial plots using Plotnine in conjunction with `geodatasets` and `geopandas` to visualize geographical data, such as population distribution on a map. ```python from plotnine import * import geodatasets import geopandas as gp chicago = gp.read_file(geodatasets.get_path("geoda.chicago_commpop")) ( ggplot(chicago, aes(fill="POP2010")) + geom_map() + coord_fixed() + theme_minimal() + labs(title="Chicago Population in 2010") ) ``` -------------------------------- ### Customize Colorbar Guide in Plotnine Source: https://plotnine.org/reference/guide/scale-basics Shows how to customize a colorbar guide by passing arguments to `guide_colorbar()` within the `guides()` function. This example specifically demonstrates how to reverse the orientation of the colorbar in the legend. ```python p = ( ggplot(mpg, aes("displ", "hwy", color="cyl")) + geom_point() + theme(legend_key_size=30) ) p p + guides(color=guide_colorbar(reverse=True)) ``` -------------------------------- ### Plotnine geom_smooth Example Setup and Imports Source: https://plotnine.org/reference/reference/geom_smooth This Python code snippet demonstrates the initial setup for using `geom_smooth` in Plotnine, including necessary imports for plotting functions, aesthetic mappings, data, and theme configuration. It sets the default theme to Matplotlib for consistent styling. ```Python from plotnine import ggplot, aes, geom_point, geom_smooth, labs, theme_matplotlib, theme_set from plotnine.data import mpg theme_set(theme_matplotlib()) ``` -------------------------------- ### Install Plotnine Development Version from GitHub Source: https://plotnine.org/reference/guide/install Instructions to install the latest development version of Plotnine directly from its GitHub repository using pip or uv. This is useful for accessing bugfixes or new features not yet available in the official release. ```bash # Using pip: $ pip install git+https://github.com/has2k1/plotnine.git # Using uv: $ uv pip install git+https://github.com/has2k1/plotnine.git ``` -------------------------------- ### Setup Plotnine Base Plot for Theme Examples Source: https://plotnine.org/reference/guide/themes-premade Initializes a `ggplot` object using the `penguins` dataset. It sets aesthetic mappings for x, y, and color, adds geometric points, configures a continuous x-axis scale, applies facet wrapping by species, and includes a subtitle. This base plot serves as the foundation for demonstrating different 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") ) ``` -------------------------------- ### Installing ipywidgets Source: https://plotnine.org/reference/tutorials/miscellaneous-using-notebook-widgets Provides commands to install ipywidgets using pip for general Python environments, and specific commands for enabling widgets in Jupyter Notebooks and JupyterLab. ```shell pip install ipywidgets # for jupyter notebooks: jupyter nbextension enable --py widgetsnbextension # for jupyter lab (requires npm): npm i @jupyter-widgets/jupyterlab-manager ``` -------------------------------- ### Setup Plotnine Environment Source: https://plotnine.org/reference/guide/position-adjustments Imports necessary libraries from plotnine, including the main ggplot object and the diamonds dataset, to prepare the environment for plotting examples. ```python from plotnine import * from plotnine.data import diamonds ``` -------------------------------- ### Plotnine Layer: setup Method Source: https://plotnine.org/reference/reference/layer Prepares the layer for plot building, providing access to data, mapping, and environment. ```APIDOC setup(plot) Prepare layer for the plot building Give the layer access to the data, mapping and environment ``` -------------------------------- ### Install Plotnine using pip Source: https://plotnine.org/reference/guide/overview This snippet provides the command to install the Plotnine library using pip, the Python package installer. It's a prerequisite for using Plotnine functionalities. ```Python pip install plotnine ``` -------------------------------- ### Install Plotnine with Extra Packages Source: https://plotnine.org/reference/guide/install Install Plotnine along with optional extra packages like adjustText, geopandas, scikit-learn, and scikit-misc for additional functionality. Use 'plotnine[extra]' to include these dependencies in a single installation command. ```bash # Using pip: $ pip install 'plotnine[extra]' # Using uv: $ uv pip install 'plotnine[extra]' # Using conda: $ conda install -c conda-forge 'plotnine[extra]' ``` -------------------------------- ### Import necessary Plotnine and Pandas modules for examples Source: https://plotnine.org/reference/reference/geom_tile Imports `pandas`, `numpy`, and various components from `plotnine` including `ggplot`, `aes`, `geom_tile`, `geom_text`, scaling functions, coordinate systems, and theme elements, preparing the environment for plotting examples. ```Python import pandas as pd import numpy as np from plotnine import ( ggplot, aes, geom_tile, geom_text, scale_y_reverse, scale_y_discrete, scale_fill_brewer, scale_color_manual, coord_equal, theme, theme_void, element_blank, element_rect, element_text, ) ``` -------------------------------- ### Plotnine Example Imports for Data Visualization Source: https://plotnine.org/reference/reference/scale_shape_identity Essential import statements for setting up a plotnine environment, including core plotnine components, data manipulation libraries like polars, and numerical operations with numpy, preparing for various plotting 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 ``` -------------------------------- ### Create a basic histogram with plotnine Source: https://plotnine.org/reference/reference/geom_histogram Demonstrates how to create a simple histogram using `ggplot` and `geom_histogram` in plotnine to visualize the distribution of 'carat' from the 'diamonds' dataset. This serves as the fundamental setup for all subsequent histogram examples. ```Python ( ggplot(diamonds, aes(x="carat")) + geom_histogram() ) ``` -------------------------------- ### Plotnine scale_size_manual expand parameter examples Source: https://plotnine.org/reference/reference/scale_size_manual Examples demonstrating the different ways to specify the `expand` parameter for `plotnine.scale_size_manual`, showing how multiplicative and additive constants affect scale expansion. ```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. ``` -------------------------------- ### Import necessary modules for Plotnine example Source: https://plotnine.org/reference/reference/theme_classic Imports `ggplot`, `aes`, `labs`, `theme_classic`, `geom_point` from `plotnine` and `mtcars` dataset from `plotnine.data`. ```python from plotnine import ggplot, aes, labs, theme_classic, geom_point from plotnine.data import mtcars ``` -------------------------------- ### Import Plotnine Modules and Load MPG Data Source: https://plotnine.org/reference/gallery/geom_bar Imports essential components from the plotnine library, including ggplot, aes, geom_bar, coord_flip, and theme_classic, along with the mpg dataset for plotting examples. ```python from plotnine import ggplot, aes, geom_bar, coord_flip, theme_classic from plotnine.data import mpg ``` -------------------------------- ### plotnine.themes.themeable.legend_box_just API Reference Source: https://plotnine.org/reference/reference/legend_box_just Detailed API documentation for the `legend_box_just` function, which controls the justification of guide boxes within plotnine themes. ```APIDOC legend_box_just(theme_element) Justification of guide boxes Parameters: theme_element : Literal["left", "right", "center", "top", "bottom", "baseline"] = None If `None`, the value that will apply depends on `legend_box`. ``` -------------------------------- ### Define plotnine.guides function signature Source: https://plotnine.org/reference/reference/guides The `guides` function in plotnine is used to assign or remove a particular guide to the scale of an aesthetic. It allows customization of how different aesthetic scales (like alpha, color, size) are represented in plots. ```Python guides( alpha=None, color=None, fill=None, linetype=None, shape=None, size=None, stroke=None, colour=None ) ``` -------------------------------- ### Initialize and Run the PyQt5 Application Source: https://plotnine.org/reference/tutorials/miscellaneous-a-pyqt5-application This final part of the script initializes the `QApplication` instance, ensuring only one exists to prevent crashes. It then creates an instance of the `Window` class, displays it, and starts the PyQt5 event loop, making the GUI interactive. ```python # To prevent random crashes when rerunning the code, # first check if there is instance of the app before creating another. app = QApplication.instance() if app is None: app = QApplication(sys.argv) main = Window() main.show() app.exec_() ``` -------------------------------- ### Import Plotnine and Sample Data Source: https://plotnine.org/reference/guide/operators This snippet imports the necessary modules from Plotnine and loads the 'mpg' dataset, which is used in subsequent examples. ```python from plotnine import * from plotnine.data import mpg ``` -------------------------------- ### Plot Polars DataFrame with Plotnine using Pipe Operator Source: https://plotnine.org/reference/guide/introduction This Python example illustrates Plotnine's support for Polars DataFrames and the use of the `>>` operator for data piping. It filters the penguins dataset to 'Adelie' species using Polars, then directly pipes the filtered data into a Plotnine scatter plot, demonstrating a concise workflow. ```Python import polars as pl pl_penguins = pl.from_pandas(penguins) ( # polars: subset rows ---- pl_penguins.filter(pl.col("species") == "Adelie") # # pipe to plotnine ---- >> ggplot(aes("bill_length_mm", "bill_depth_mm", fill="species")) + geom_point() + labs(title="Adelie penguins") ) ``` -------------------------------- ### Set Guide Labels Using `name` Argument in Plotnine Scales Source: https://plotnine.org/reference/guide/scale-basics This example illustrates how to customize the labels of plot guides (axes and legends) by using the `name=` argument within various scale functions, such as `scale_x_continuous()`, `scale_y_continuous()`, and `scale_color_discrete()`. This provides granular control over individual guide titles. ```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") ) ``` -------------------------------- ### Plotnine Basic Setup and Theme Application Source: https://plotnine.org/reference/reference/scale_fill_continuous This Python snippet demonstrates how to import essential plotnine modules and set a default matplotlib theme for all subsequent plots. ```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()) ``` -------------------------------- ### Setup Plotnine Environment Source: https://plotnine.org/reference/guide/facets Imports necessary libraries from plotnine for data visualization and data loading, including the main plotnine module and sample datasets like `mpg` and `penguins`. ```python from plotnine import * from plotnine.data import mpg, penguins ``` -------------------------------- ### Importing Plotnine and Pandas for after_scale Examples Source: https://plotnine.org/reference/reference/examples/after_scale-preview Imports necessary libraries: `pandas` for data handling and key components from `plotnine` including `ggplot`, `aes`, `after_scale`, `geom_bar`, and `theme_classic`. ```python import pandas as pd from plotnine import ggplot, aes, after_scale, geom_bar, theme_classic ``` -------------------------------- ### Initialize Plotnine Theming Environment Source: https://plotnine.org/reference/reference/examples/theme-preview Imports necessary plotnine modules and sets `theme_void` as the base theme. This ensures that subsequent modifications are transparently applied without interference from default theme elements. ```python from plotnine import ( ggplot, aes, geom_point, facet_grid, labs, guide_legend, guides, theme, element_text, element_line, element_rect, theme_set, theme_void, ) from plotnine.data import mtcars # We use theme_void as the base theme so that the modifications # we make in the code are transparent in the output theme_set(theme_void()) ``` -------------------------------- ### plotnine.guides Function Parameters Source: https://plotnine.org/reference/reference/guides Detailed documentation for the parameters of the `plotnine.guides` function, specifying their types, default values, and purpose for controlling aesthetic scales. ```APIDOC guides 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 Scale Parameter Attributes Reference Source: https://plotnine.org/reference/reference/scale_color_gradient Detailed API documentation for the attributes that can be configured for scales in plotnine, including their types, descriptions, and examples for usage. This covers parameters like name, breaks, limits, labels, expansion, guide, and more. ```APIDOC Parameter Attributes: name: str | None = None Description: 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: ContinuousBreaksUser = True Description: Major breaks limits: ContinuousLimitsUser = None Description: Limits of the scale. Most commonly, these are the minimum & maximum values for the scale. If not specified they are derived from the data. It may also be a function that takes the derived limits and transforms them into the final limits. labels: ScaleLabelsUser = True Description: 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 Description: 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", "colorbar"] | None = "colorbar" Description: Controls the guide type. na_value: str = "#7F7F7F" Description: Color of missing values. aesthetics: Sequence[ScaledAestheticsName] = () Description: Aesthetics affected by this scale. These are defined by each scale and the user should probably not change them. Have fun. rescaler: PRescale = rescale Description: Function to rescale data points so that they can be handled by the palette. Default is to rescale them onto the [0, 1] range. Scales that inherit from this class may have another default. oob: PCensor = censor Description: Function to deal with out of bounds (limits) data points. Default is to turn them into `np.nan`, which then get dropped. minor_breaks: MinorBreaksUser = True Description: If a list-like, it is the minor breaks points. If an integer, it is the number of minor breaks between any set of major breaks. If a function, it should have the signature `func(limits)` and return a list-like of consisting of the minor break points. If `None`, no minor breaks are calculated. The default is to automatically calculate them. trans: TransUser = None Description: The transformation of the scale. Either name of a trans function or a trans function. See `mizani.transforms` for possible options. ``` -------------------------------- ### Restrict Color Scale Data Range in Plotnine Source: https://plotnine.org/reference/guide/scale-basics Demonstrates how to restrict the data range for a continuous color scale using `scale_color_continuous` with the `limits` argument in Plotnine. This example shows how to cap the upper bound of the color mapping. ```python p = ggplot(huron, aes("year", "level", color="year")) + geom_line() p p + scale_color_continuous(limits=[None, 1900]) ``` -------------------------------- ### Customize aesthetic scales with scale_*() functions Source: https://plotnine.org/reference/guide/overview The `scale_*()` functions allow customization of visual elements derived from data mappings, including color palettes, axis limits, and guide names. This example applies a 'viridis' color palette to the 'displ' aesthetic. ```Python ( ggplot(mpg, aes("cty", "hwy", color="displ")) + geom_point() + scale_color_continuous(name="displ (VIRIDIS)", cmap_name="viridis") ) ``` -------------------------------- ### Add geometric objects to a Plotnine plot Source: https://plotnine.org/reference/guide/overview Functions starting with `geom_*()` define how mapped data is rendered visually, such as points or lines. This example adds a scatterplot (`geom_point()`) and a linear trend line (`geom_smooth()`) to visualize city vs. highway mileage. ```Python ( ggplot(mpg, aes("cty", "hwy")) # to create a scatterplot + geom_point() # to fit and overlay a loess trendline + geom_smooth(method="lm", color="blue") ) ``` -------------------------------- ### Apply Position Scale Transformations (Reverse, Log10) in Plotnine Source: https://plotnine.org/reference/guide/scale-basics This example shows how to apply common transformations to position scales (x and y axes) in Plotnine. It demonstrates reversing the x-axis using `scale_x_reverse()` and applying a base-10 logarithmic transformation to the y-axis using `scale_y_log10()`. ```Python (ggplot(mpg, aes("displ", "hwy")) + geom_point() + scale_x_reverse() + scale_y_log10()) ``` -------------------------------- ### Plotnine v0.14 Initial Imports and Theme Setup Source: https://plotnine.org/reference/blog/2024/11/version-0.14.0/index This Python snippet demonstrates the essential imports from `pandas` and `plotnine` required to start working with plotnine v0.14. It also shows how to set a default theme globally using `theme_set(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()); ``` -------------------------------- ### Initialize Plotnine Environment and Set Theme Source: https://plotnine.org/reference/reference/examples/labs-preview This snippet imports essential modules from the `plotnine` library, including `ggplot`, `aes`, `labs`, `geom_point`, and various themes. It then applies the `theme_538` to the plotting environment, providing a distinct visual style for subsequent plots. ```Python from plotnine import ggplot, aes, labs, geom_point, theme, theme_538, theme_set from plotnine.data import mtcars theme_set(theme_538()) ``` -------------------------------- ### Adding a Single Vertical Line to a Plotnine Scatter Plot Source: https://plotnine.org/reference/reference/geom_vline This example demonstrates how to incorporate a single vertical guide line into an existing scatter plot using `geom_vline()`. The line is positioned at a specific x-intercept value (e.g., 5), serving to highlight a particular point or region on the x-axis. ```python ( ggplot(mpg, aes(x="displ", y="hwy")) + geom_point() + geom_vline(xintercept=5) # add one vertical line + labs(x="displacement", y="horsepower") ) ``` -------------------------------- ### Automatically Apply ColorBrewer Palette in Plotnine Source: https://plotnine.org/reference/guide/scale-basics This example illustrates using `scale_color_brewer()` to automatically apply a ColorBrewer palette for color mapping based on data values. It demonstrates how Plotnine handles multiple levels of a discrete variable by assigning distinct colors from the chosen palette. ```Python ( ggplot(mpg, aes("displ", "hwy", color="class")) + geom_point() + scale_color_brewer(type="qual", palette=2) ) ``` -------------------------------- ### Import Plotnine Modules for Classic Theme Example Source: https://plotnine.org/reference/reference/examples/theme_classic-preview This snippet imports essential components from the `plotnine` library, including `ggplot` for creating plots, `aes` for aesthetic mappings, `labs` for customizing labels, `theme_classic` for applying a minimalist theme, and `geom_point` for generating scatter plots. It also imports the `mtcars` dataset from `plotnine.data` for demonstration purposes. ```python from plotnine import ggplot, aes, labs, theme_classic, geom_point from plotnine.data import mtcars ``` -------------------------------- ### Create a Basic Scatter Plot with Plotnine Source: https://plotnine.org/reference/guide/introduction This Python snippet demonstrates how to create a simple scatter plot using Plotnine. It visualizes the relationship between bill length and bill depth for different penguin species from the included `penguins` dataset, coloring points by species. ```Python from plotnine import ggplot, aes, geom_point, labs from plotnine.data import penguins ( ggplot(penguins, aes("bill_length_mm", "bill_depth_mm", color="species")) + geom_point() ) ``` -------------------------------- ### plotnine.scale_fill_datetime Initialization Parameters Source: https://plotnine.org/reference/reference/scale_fill_datetime Detailed documentation for the initialization parameters of `plotnine.scale_fill_datetime`, including type, default values, and a description of each parameter's purpose and usage. ```APIDOC cmap_name: str = 'viridis' 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. date_breaks: str | None = None A string giving the distance between major breaks. For example '2 weeks', '5 years'. If specified, date_breaks takes precedence over breaks. date_labels: str | None = None Format string for the labels. See strftime. If specified, date_labels takes precedence over labels. date_minor_breaks: str | None = None A string giving the distance between minor breaks. For example '2 weeks', '5 years'. If specified, date_minor_breaks takes precedence over minor_breaks. ``` -------------------------------- ### Import Plotnine and Load Sample Data Source: https://plotnine.org/reference/reference/examples/facet_wrap-preview Imports necessary components from the `plotnine` library, including `ggplot`, `aes`, `geom_point`, `labs`, `facet_wrap`, and `theme`. It also loads the `mpg` dataset, which is commonly used for examples in `plotnine`. ```python from plotnine import ggplot, aes, geom_point, labs, facet_wrap, theme from plotnine.data import mpg ``` -------------------------------- ### plotnine.scale_fill_gray Function API Reference Source: https://plotnine.org/reference/reference/scale_fill_gray Detailed API documentation for the `scale_fill_gray` function in plotnine, including its signature, initial parameters (`start`, `end`), and various parameter attributes (`name`, `breaks`, `limits`, `labels`, `expand`, `guide`, `na_value`, `aesthetics`, `drop`, `na_translate`) with their types, default values, and descriptions. ```APIDOC scale_fill_gray( start=0.2, end=0.8, *, name=None, breaks=True, limits=None, labels=True, expand=None, guide="legend", na_value="#7F7F7F", aesthetics=(), drop=True, na_translate=True ) Parameters: start: float = 0.2 Grey value at low end of palette. end: float = 0.8 Grey value at high end of palette. 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: str = "#7F7F7F" Color of missing values. 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. ``` -------------------------------- ### Styling Multiple Vertical Lines in Plotnine Plots Source: https://plotnine.org/reference/reference/geom_vline This advanced example showcases how to customize the appearance of multiple vertical lines. It demonstrates setting individual colors, sizes (thickness), and a consistent line type (e.g., dotted) for the lines. This allows for fine-grained control over the visual emphasis and clarity of the guide lines. ```python ( ggplot(mpg, aes(x="displ", y="hwy")) + geom_point() + geom_vline( xintercept=[4, 5, 7], colour=["red", "orange", "green"], # add colour size=[1, 2, 3], # set line thickness linetype="dotted" # set line type ) + labs(x="displacement", y="horsepower") ) ``` -------------------------------- ### Import Plotnine Modules and Load Diamonds Dataset Source: https://plotnine.org/reference/reference/examples/geom_histogram-preview This snippet imports necessary modules from `plotnine` for creating histograms and related visualizations, along with the `diamonds` dataset from `plotnine.data` and `percent_format` from `mizani.formatters`. It sets up the environment for plotting. ```python from plotnine import ( ggplot, aes, after_stat, geom_histogram, facet_wrap, facet_grid, coord_flip, scale_y_continuous, scale_y_sqrt, scale_y_log10, scale_fill_manual, theme_bw, theme_xkcd, ) from plotnine.data import diamonds from mizani.formatters import percent_format ``` -------------------------------- ### Plotting Initial Density Curve with Plotnine Source: https://plotnine.org/reference/reference/examples/geom_density-preview This snippet initializes data using `pandas` and `numpy` and then generates a basic density plot using `ggplot` and `geom_density` from `plotnine`. ```Python n = 101 df = pd.DataFrame({"x": np.arange(n)}) ( ggplot(df, aes("x")) + geom_density() ) ``` -------------------------------- ### Merge Multiple Guides with Same Title in Plotnine Source: https://plotnine.org/reference/guide/scale-basics Illustrates a more advanced guide customization technique: merging multiple distinct guides (e.g., for color, size, and shape) into a single legend. This is achieved by assigning them all the same title using `guide_legend()` within the `guides()` function. ```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") ) ) ``` -------------------------------- ### Import plotnine modules for line plot examples Source: https://plotnine.org/reference/reference/geom_line Imports core plotnine components, including `ggplot`, `aes`, `geom_line`, `facet_wrap`, `labs`, `scale_x_datetime`, `element_text`, `theme_538`, and the `meat` dataset, typically used to set up an environment for creating line plots. ```python from plotnine import ( ggplot, aes, geom_line, facet_wrap, labs, scale_x_datetime, element_text, theme_538 ) from plotnine.data import meat ``` -------------------------------- ### plotnine.theme Methods Overview Source: https://plotnine.org/reference/reference/theme Lists the key methods available for the `plotnine.theme` class, which allow for further manipulation and application of theme properties. These methods extend the functionality of the base theme class. ```APIDOC plotnine.theme.add_theme plotnine.theme.apply plotnine.theme.get_margin plotnine.theme.setup plotnine.theme.to_retina ``` -------------------------------- ### API Parameter: guide Source: https://plotnine.org/reference/reference/scale_stroke_continuous Documents the 'guide' parameter, which specifies the type of guide to use for the scale, defaulting to 'legend'. ```APIDOC guide: [Literal]["legend"] | None = "legend" ``` -------------------------------- ### Initialize Plotnine Environment and Inspect Data Source: https://plotnine.org/reference/gallery/geom_density Sets up the Python environment by importing necessary libraries like pandas, numpy, and plotnine components. It then displays the first few rows of the `mpg` dataset to provide an overview of the data structure used in the examples. ```python import pandas as pd import numpy as np from plotnine import ( ggplot, aes, after_stat, geom_density, geom_histogram, geom_vline, geom_rect, labs, annotate, theme_tufte, ) from plotnine.data import mpg ``` ```python mpg.head() ``` -------------------------------- ### plotnine.scale_color_gradientn Initialization Parameters Source: https://plotnine.org/reference/reference/scale_color_gradientn Detailed API documentation for the key initialization parameters of the `scale_color_gradientn` function, specifying their types, default values, and a description of their purpose. ```APIDOC colors: Sequence[str] = '#832424' Description: List of colors values: Sequence[float] | None = None Description: list of points in the range [0, 1] at which to place each color. Must be the same size as `colors`. Default to evenly space the colors ``` -------------------------------- ### Parameter: guide Source: https://plotnine.org/reference/reference/scale_size_area Determines the type of guide for the scale, defaulting to 'legend'. ```APIDOC guide: Literal["legend"] | None = "legend" ``` -------------------------------- ### Plotnine Layer: setup_data Method Source: https://plotnine.org/reference/reference/layer Prepares or modifies data specifically for plotting within the layer. ```APIDOC setup_data() Prepare/modify data for plotting ``` -------------------------------- ### Parameter: guide Source: https://plotnine.org/reference/reference/scale_fill_gradient2 Determines the type of guide for the scale, either 'legend' or 'colorbar'. ```APIDOC guide: Literal["legend", "colorbar"] | None = "colorbar" ``` -------------------------------- ### API Documentation for plotnine.themes.themeable.panel_grid_minor_x Source: https://plotnine.org/reference/reference/panel_grid_minor_x Provides the API documentation for the `panel_grid_minor_x` themeable element in plotnine, detailing its function signature, purpose, and parameters. ```APIDOC plotnine.themes.themeable.panel_grid_minor_x: signature: panel_grid_minor_x(theme_element) description: Vertical minor grid lines parameters: theme_element: type: element_line ```