diff --git a/plotnine/_mpl/_plot_side_space.py b/plotnine/_mpl/_plot_side_space.py index 16712e406..30b1d1fb9 100644 --- a/plotnine/_mpl/_plot_side_space.py +++ b/plotnine/_mpl/_plot_side_space.py @@ -4,8 +4,8 @@ titles and offsetboxes that are anchored to axes are currently considered. Internally, this module assumes that the margins (left margin, etc.) which are -differences between ``Axes.get_tightbbox`` and ``Axes.bbox`` are independent of -Axes position. This may fail if ``Axes.adjustable`` is ``datalim`` as well as +differences between `Axes.get_tightbbox` and `Axes.bbox` are independent of +Axes position. This may fail if `Axes.adjustable` is `datalim` as well as such cases as when left or right margin are affected by xlabel. """ from __future__ import annotations diff --git a/plotnine/_mpl/_plotnine_tight_layout.py b/plotnine/_mpl/_plotnine_tight_layout.py index cfe8709d3..13d233628 100644 --- a/plotnine/_mpl/_plotnine_tight_layout.py +++ b/plotnine/_mpl/_plotnine_tight_layout.py @@ -4,8 +4,8 @@ titles and offsetboxes that are anchored to axes are currently considered. Internally, this module assumes that the margins (left margin, etc.) which are -differences between ``Axes.get_tightbbox`` and ``Axes.bbox`` are independent of -Axes position. This may fail if ``Axes.adjustable`` is ``datalim`` as well as +differences between `Axes.get_tightbbox` and `Axes.bbox` are independent of +Axes position. This may fail if `Axes.adjustable` is `datalim` as well as such cases as when left or right margin are affected by xlabel. """ from __future__ import annotations diff --git a/plotnine/coords/coord.py b/plotnine/coords/coord.py index 349e33e0f..c43bf18fd 100644 --- a/plotnine/coords/coord.py +++ b/plotnine/coords/coord.py @@ -99,7 +99,7 @@ def aspect(self, panel_params: panel_view) -> float | None: Return desired aspect ratio for the plot If not overridden by the subclass, this method - returns ``None``, which means that the coordinate + returns `None`, which means that the coordinate system does not influence the aspect ratio. """ return None diff --git a/plotnine/coords/coord_cartesian.py b/plotnine/coords/coord_cartesian.py index 5df9ddddd..932856c1a 100644 --- a/plotnine/coords/coord_cartesian.py +++ b/plotnine/coords/coord_cartesian.py @@ -27,16 +27,13 @@ class coord_cartesian(coord): Parameters ---------- - xlim : None | (float, float) - Limits for x axis. If None, then they are - automatically computed. - ylim : None | (float, float) - Limits for y axis. If None, then they are - automatically computed. - expand : bool - If `True`, expand the coordinate axes by - some factor. If `False`, use the limits - from the data. + xlim : tuple[float, float], default=None + Limits for x axis. If None, then they are automatically computed. + ylim : tuple[float, float], default=None + Limits for y axis. If None, then they are automatically computed. + expand : bool, default=True + If `True`, expand the coordinate axes by some factor. If `False`, + use the limits from the data. """ is_linear = True diff --git a/plotnine/coords/coord_fixed.py b/plotnine/coords/coord_fixed.py index f6e0f9a67..061c24bd8 100644 --- a/plotnine/coords/coord_fixed.py +++ b/plotnine/coords/coord_fixed.py @@ -19,24 +19,22 @@ class coord_fixed(coord_cartesian): ---------- ratio : float Desired aspect_ratio (:math:`y/x`) of the panel(s). - Default is 1. - xlim : None | (float, float) - Limits for x axis. If None, then they are - automatically computed. - ylim : None | (float, float) - Limits for y axis. If None, then they are - automatically computed. - expand : bool - If `True`, expand the coordinate axes by - some factor. If `False`, use the limits - from the data. + xlim : tuple[float, float], default=None + Limits for x axis. If None, then they are automatically computed. + ylim : tuple[float, float], default=None + Limits for y axis. If None, then they are automatically computed. + expand : bool, default=True + If `True`, expand the coordinate axes by some factor. If `False`, + use the limits from the data. Notes ----- To specify aspect ratio of the visual size for the axes use the - [](`~plotnine.themes.themeable.aspect_ratio`) themeable:: + [](`~plotnine.themes.themeable.aspect_ratio`) themeable. - ggplot(data, aes('x', 'y')) + theme(aspect_ratio=0.5) + ```python + ggplot(data, aes('x', 'y')) + theme(aspect_ratio=0.5) + ``` When changing the `aspect_ratio` in either way, the `width` of the panel remains constant (as derived from the diff --git a/plotnine/coords/coord_flip.py b/plotnine/coords/coord_flip.py index 8cff242c3..b31cc9389 100644 --- a/plotnine/coords/coord_flip.py +++ b/plotnine/coords/coord_flip.py @@ -21,23 +21,19 @@ class coord_flip(coord_cartesian): """ Flipped cartesian coordinates - The horizontal becomes vertical, and vertical becomes - horizontal. This is primarily useful for converting - geoms and statistics which display y conditional - on x, to x conditional on y. + The horizontal becomes vertical, and vertical becomes horizontal. + This is primarily useful for converting geoms and statistics which + display y conditional on x, to x conditional on y. Parameters ---------- - xlim : None | (float, float) - Limits for x axis. If None, then they are - automatically computed. - ylim : None | (float, float) - Limits for y axis. If None, then they are - automatically computed. - expand : bool - If `True`, expand the coordinate axes by - some factor. If `False`, use the limits - from the data. + xlim : tuple[float, float], default=None + Limits for x axis. If None, then they are automatically computed. + ylim : tuple[float, float], default=None + Limits for y axis. If None, then they are automatically computed. + expand : bool, default=True + If `True`, expand the coordinate axes by some factor. If `False`, + use the limits from the data. """ def labels(self, cur_labels: labels_view) -> labels_view: diff --git a/plotnine/coords/coord_trans.py b/plotnine/coords/coord_trans.py index 06efbdf16..f49e7a9a3 100644 --- a/plotnine/coords/coord_trans.py +++ b/plotnine/coords/coord_trans.py @@ -32,21 +32,16 @@ class coord_trans(coord): Parameters ---------- x : str | trans - Name of transform or `trans` class to - transform the x axis + Name of transform or `trans` class to transform the x axis y : str | trans - Name of transform or `trans` class to - transform the y axis - xlim : None | (float, float) - Limits for x axis. If None, then they are - automatically computed. - ylim : None | (float, float) - Limits for y axis. If None, then they are - automatically computed. - expand : bool - If `True`, expand the coordinate axes by - some factor. If `False`, use the limits - from the data. + Name of transform or `trans` class to transform the y axis + xlim : tuple[float, float], default=None + Limits for x axis. If None, then they are automatically computed. + ylim : tuple[float, float], default=None + Limits for y axis. If None, then they are automatically computed. + expand : bool, default=True + If `True`, expand the coordinate axes by some factor. If `False`, + use the limits from the data. """ trans_x: Trans diff --git a/plotnine/data/__init__.py b/plotnine/data/__init__.py index 1cb5065a0..dac9fa76e 100644 --- a/plotnine/data/__init__.py +++ b/plotnine/data/__init__.py @@ -91,34 +91,31 @@ def _unordered_categories(df, columns): mtcars.__doc__ = """ Motor Trend Car Road Tests -.. rubric:: Description +**Description** The data was extracted from the 1974 *Motor Trend* US magazine, and comprises fuel consumption and 10 aspects of automobile design and performance for 32 automobiles (1973–74 models). - -.. rubric:: Format +**Format** A data frame with 32 observations on 11 variables. -====== ========================================= -Column Description -====== ========================================= -mpg Miles/(US) gallon -cyl Number of cylinders -disp Displacement (cu.in.) -hp Gross horsepower -drat Rear axle ratio -wt Weight (1000 lbs) -qsec 1/4 mile time -vs V/S -am Transmission (0 = automatic, 1 = manual) -gear Number of forward gears -carb Number of carburetors -====== ========================================= - -.. rubric:: Source +| Column | Description | +|--------|------------------------------------------| +| mpg | Miles/(US) gallon | +| cyl | Number of cylinders | +| disp | Displacement (cu.in.) | +| hp | Gross horsepower | +| drat | Rear axle ratio | +| wt | Weight (1000 lbs) | +| qsec | 1/4 mile time | +| vs | V/S | +| am | Transmission (0 = automatic, 1 = manual) | +| gear | Number of forward gears | +| carb | Number of carburetors | + +**Source** Henderson and Velleman (1981), Building multiple regression models interactively. *Biometrics*, **37**, 391–411. @@ -134,21 +131,19 @@ def _unordered_categories(df, columns): huron.__doc__ = """ Level of Lake Huron 1875–1972 -.. rubric:: Description +**Description** Annual measurements of the level, in feet, of Lake Huron 1875–1972. -.. rubric:: Format +**Format** -========= ============== -Column Description -========= ============== -year Year -level Water level -decade Decade -========= ============== +| Column | Description | +|--------|-------------| +| year | Year | +| level | Water level | +| decade | Decade | -.. rubric:: Source +**Source** Brockwell, P. J. and Davis, R. A. (1991). Time Series and Forecasting Methods. Second edition. Springer, New York. Series A, page 555. @@ -160,7 +155,7 @@ def _unordered_categories(df, columns): seals.__doc__ = """ Vector field of seal movements. -.. rubric:: Description +**Description** This vector field was produced from the data described in Brillinger, D.R., Preisler, H.K., Ager, A.A. and Kie, J.G. @@ -169,53 +164,49 @@ def _unordered_categories(df, columns): of Brillinger, D.R., "Learning a potential function from a trajectory", Signal Processing Letters. December (2007). -.. rubric:: Format +**Format** A data frame with 1155 rows and 4 variables -=========== =================== -Column Description -=========== =================== -lat Latitude -long Longitude -delta_long Change in Longitude -delta_lat Change in Latitude -=========== =================== +| Column | Description | +|------------|---------------------| +| lat | Latitude | +| long | Longitude | +| delta_long | Change in Longitude | +| delta_lat | Change in Latitude | -.. rubric:: References +**References** -http://www.stat.berkeley.edu/~brill/Papers/jspifinal.pdf +[](http://www.stat.berkeley.edu/~brill/Papers/jspifinal.pdf) """ economics.__doc__ = """ US economic time series. -.. rubric:: Description +**Description** This dataset was produced from US economic time series data available from http://research.stlouisfed.org/fred2. `economics` is in "wide" format, `economics_long` is in "long" format. -.. rubric:: Format +**Format** A data frame with 478 rows and 6 variables -========= ========================================================== -Column Description -========= ========================================================== -date Month of data collection -psavert personal savings rate [1_] -pce personal consumption expenditures, in billions of dollars [2_] -unemploy number of unemployed in thousands, [3_] -uempmed median duration of unemployment, in week [4_] -pop total population, in thousands [5_] -========= ========================================================== - -.. _1: http://research.stlouisfed.org/fred2/series/PSAVERT/ -.. _2: http://research.stlouisfed.org/fred2/series/PCE -.. _3: http://research.stlouisfed.org/fred2/series/UNEMPLOY -.. _4: http://research.stlouisfed.org/fred2/series/UEMPMED -.. _5: http://research.stlouisfed.org/fred2/series/POP +| Column | Description | +|----------|----------------------------------------------------------------| +| date | Month of data collection | +| psavert | personal savings rate [^1] | +| pce | personal consumption expenditures, in billions of dollars [^2] | +| unemploy | number of unemployed in thousands [^3] | +| uempmed | median duration of unemployment, in week [^4] | +| pop | total population, in thousands [^5] | + +[^1]: [](http://research.stlouisfed.org/fred2/series/PSAVERT) +[^2]: [](http://research.stlouisfed.org/fred2/series/PCE) +[^3]: [](http://research.stlouisfed.org/fred2/series/UNEMPLOY) +[^4]: [](http://research.stlouisfed.org/fred2/series/UEMPMED) +[^5]: [](http://research.stlouisfed.org/fred2/series/POP) """ economics_long.__doc__ = economics.__doc__ @@ -223,99 +214,101 @@ def _unordered_categories(df, columns): presidential.__doc__ = """ Terms of 11 presidents from Eisenhower to Obama. -.. rubric:: Description +**Description** The names of each president, the start and end date of their term, and their party of 11 US presidents from Eisenhower to Obama. -========== =========================== -Column Description -========== =========================== -name Name of president -start Start of presidential term -end End of presidential term -party Political Party -========== =========================== - -.. rubric:: Format +**Format** A data frame with 11 rows and 4 variables + +| Column | Description | +|--------|----------------------------| +| name | Name of president | +| start | Start of presidential term | +| end | End of presidential term | +| party | Political Party | + """ txhousing.__doc__ = """ Housing sales in TX. -.. rubric:: Description +**Description** Information about the housing market in Texas provided by the TAMU real estate center, http://recenter.tamu.edu/. - -.. rubric:: Format +**Format** A data frame with 8602 observations and 9 variables: -========= =============================================== -Column Description -========= =============================================== -city Name of MLS area -year Year -month Month -sales Number of sales -volume Total value of sales -median Median sale price -listings Total active listings -inventory "Months inventory": amount of time it would \n - take to sell all current listings at current \n - pace of sales. -date Date -========= =============================================== ++-----------+-----------------------------------------------+ +| Column | Description | ++===========+===============================================+ +| city | Name of MLS area | ++-----------+-----------------------------------------------+ +| year | Year | ++-----------+-----------------------------------------------+ +| month | Month | ++-----------+-----------------------------------------------+ +| sales | Number of sales | ++-----------+-----------------------------------------------+ +| volume | Total value of sales | ++-----------+-----------------------------------------------+ +| median | Median sale price | ++-----------+-----------------------------------------------+ +| listings | Total active listings | ++-----------+-----------------------------------------------+ +| inventory | "Months inventory": amount of time it would | +| | take to sell all current listings at current | +| | pace of sales. | ++-----------+-----------------------------------------------+ +| date | Date | ++-----------+-----------------------------------------------+ + """ luv_colours.__doc__ = """ colors in Luv space. -.. rubric:: Description +**Description** Named colors translated into Luv colour space. -luv_colours -.. rubric:: Format +**Format** A data frame with 657 observations and 4 variables: -====== ============================ -Column Description -====== ============================ -L L position in Luv colour space -u u position in Luv colour space -v v position in Luv colour space -col Colour name -====== ============================ +| Column | Description | +|--------|--------------------------------| +| L | L position in Luv colour space | +| u | u position in Luv colour space | +| v | v position in Luv colour space | +| col | Colour name | """ faithful.__doc__ = """ Old Faithful Geyser Data -.. rubric:: Description +**Description** Waiting time between eruptions and the duration of the eruption for the Old Faithful geyser in Yellowstone National Park, Wyoming, USA. -.. rubric:: Format +**Format** A data frame with 272 observations on 2 variables. -========== ======================================== -Column Description -========== ======================================== -eruptions Eruption time in mins -waiting Waiting time to next eruption (in mins) -========== ======================================== +| Column | Description | +|-----------|----------------------------------------| +| eruptions | Eruption time in mins | +| waiting W | aiting time to next eruption (in mins) | -.. rubric:: Details +**Details** A closer look at `faithful.eruptions` reveals that these are heavily rounded times originally in seconds, where multiples @@ -325,11 +318,11 @@ def _unordered_categories(df, columns): There are many versions of this dataset around: Azzalini and Bowman (1990) use a more complete version. -.. rubric:: Source +**Source** W. Härdle. -.. rubric:: References +**References** Härdle, W. (1991) *Smoothing Techniques with Implementation in S*. New York: Springer. @@ -341,26 +334,24 @@ def _unordered_categories(df, columns): faithfuld.__doc__ = """ Old Faithful Geyser Data -.. rubric:: Description +**Description** Waiting time between eruptions and the duration of the eruption for the Old Faithful geyser in Yellowstone National Park, Wyoming, USA. -.. rubric:: Format +**Format** A data frame with *grid data* for 272 observations on 2 variables and the density at those locations. -========== ======================================== -Column Description -========== ======================================== -eruptions Eruption time in mins -waiting Waiting time to next eruption (in mins) -density Density Estimate -========== ======================================== +| Column | Description | +|-----------|----------------------------------------| +| eruptions | Eruption time in mins | +| waiting W | aiting time to next eruption (in mins) | +| density D | ensity Estimate | -.. rubric:: Details +**Details** A closer look at `faithful.eruptions` reveals that these are heavily rounded times originally in seconds, where multiples @@ -370,11 +361,11 @@ def _unordered_categories(df, columns): There are many versions of this dataset around: Azzalini and Bowman (1990) use a more complete version. -.. rubric:: Source +**Source** W. Härdle. -.. rubric:: References +**References** Härdle, W. (1991) *Smoothing Techniques with Implementation in S*. New York: Springer. @@ -386,81 +377,89 @@ def _unordered_categories(df, columns): diamonds.__doc__ = """ Prices of 50,000 round cut diamonds -.. rubric:: Description +**Description** A dataset containing the prices and other attributes of almost 54,000 diamonds. The variables are as follows: -.. rubric:: Format +**Format** A data frame with 53940 rows and 10 variables: -======== ================================== -Column Description -======== ================================== -price price in US dollars ($326–$18,823) -carat weight of the diamond (0.2–5.01) -cut quality of the cut (Fair, Good, Very Good, Premium, Ideal) -color diamond colour, from J (worst) to D (best) -clarity a measurement of how clear the diamond is \n - (I1 (worst), SI1, SI2, VS1, VS2, VVS1, VVS2, IF (best)) -x length in mm (0–10.74) -y width in mm (0–58.9) -z depth in mm (0–31.8) -depth total depth percentage = z / mean(x, y) = 2 * z / (x + y) (43–79) -table width of top of diamond relative to widest point (43–95) -======== ================================== ++----------+------------------------------------------------------------+ +| Column | Description | ++==========+============================================================+ +| price | price in US dollars ($326–$18,823) | ++----------+------------------------------------------------------------+ +| carat | weight of the diamond (0.2–5.01) | ++----------+------------------------------------------------------------+ +| cut | quality of the cut (Fair, Good, Very Good, Premium, Ideal) | ++----------+------------------------------------------------------------+ +| color | diamond colour, from J (worst) to D (best) | ++----------+------------------------------------------------------------+ +| clarity | a measurement of how clear the diamond is | +| | (I1 (worst), SI1, SI2, VS1, VS2, VVS1, VVS2, IF (best)) | ++----------+------------------------------------------------------------+ +| x | length in mm (0–10.74) | ++----------+------------------------------------------------------------+ +| y | width in mm (0–58.9) | ++----------+------------------------------------------------------------+ +| z | depth in mm (0–31.8) | ++----------+------------------------------------------------------------+ +| depth | total depth percentage | +| | = z / mean(x, y) = 2 * z / (x + y) (43–79) | ++----------+------------------------------------------------------------+ +| table | width of top of diamond relative to widest point (43–95) | ++----------+------------------------------------------------------------+ """ midwest.__doc__ = """ Midwest demographics. -.. rubric:: Description +**Description** Demographic information of midwest counties -.. rubric:: Format +**Format** A data frame with 437 rows and 28 variables -===================== ============================ -Column Description -===================== ============================ -PID -county -state -area -poptotal Total population -popdensity Population density -popwhite Number of whites -popblack Number of blacks -popamerindian Number of American Indians -popasian Number of Asians -popother Number of other races -percwhite Percent white -percblack Percent black -percamerindan Percent American Indian -percasian Percent Asian -percother Percent other races -popadults Number of adults -perchsd -percollege Percent college educated -percprof Percent profession -poppovertyknown -percpovertyknown -percbelowpoverty -percchildbelowpovert -percadultpoverty -percelderlypoverty -inmetro In a metro area -category -===================== ============================ +|Column | Description | +|----------------------|------------------------------| +|PID | | +|county | | +|state | | +|area | | +|poptotal | Total population | +|popdensity | Population density | +|popwhite | Number of whites | +|popblack | Number of blacks | +|popamerindian | Number of American Indians | +|popasian | Number of Asians | +|popother | Number of other races | +|percwhite | Percent white | +|percblack | Percent black | +|percamerindan | Percent American Indian | +|percasian | Percent Asian | +|percother | Percent other races | +|popadults | Number of adults | +|perchsd | | +|percollege | Percent college educated | +|percprof | Percent profession | +|poppovertyknown | | +|percpovertyknown | | +|percbelowpoverty | | +|percchildbelowpovert | | +|percadultpoverty | | +|percelderlypoverty | | +|inmetro | In a metro area | +|category | | """ mpg.__doc__ = """ Fuel economy data from 1999 and 2008 for 38 popular models of car -.. rubric:: Description +**Description** This dataset contains a subset of the fuel economy data that the EPA makes available on http://fueleconomy.gov. @@ -468,31 +467,43 @@ def _unordered_categories(df, columns): between 1999 and 2008 - this was used as a proxy for the popularity of the car. -.. rubric:: Format +**Format** A data frame with 234 rows and 11 variables -============ ==================================================== -Column Description -============ ==================================================== -manufacturer -model -displ engine displacement, in litres -year -cyl number of cylinders -trans type of transmission -drv f = front-wheel drive, r = rear wheel drive, 4 = 4wd -cty city miles per gallon -hwy highway miles per gallon -fl -class -============ ==================================================== ++--------------+---------------------------------+ +| Column | Description | ++==============+=================================+ +| manufacturer | | ++--------------+---------------------------------+ +| model | | ++--------------+---------------------------------+ +| displ | engine displacement, in litres | ++--------------+---------------------------------+ +| year | | ++--------------+---------------------------------+ +| cyl | number of cylinders | ++--------------+---------------------------------+ +| trans | type of transmission | ++--------------+---------------------------------+ +| drv | f = front-wheel drive | +| | r = rear wheel drive | +| | 4 = 4wd | ++--------------+---------------------------------+ +| cty | city miles per gallon | ++--------------+---------------------------------+ +| hwy | highway miles per gallon | ++--------------+---------------------------------+ +| fl | | ++--------------+---------------------------------+ +| class | | ++--------------+---------------------------------+ """ msleep.__doc__ = """ An updated and expanded version of the mammals sleep dataset. -.. rubric:: Description +**Description** This is an updated and expanded version of the mammals sleep dataset. Updated sleep times and weights were taken @@ -500,27 +511,23 @@ def _unordered_categories(df, columns): framework for understanding mammalian sleep. Proceedings of the National Academy of Sciences, 104 (3):1051-1056, 2007. -.. rubric:: Format +**Format** A data frame with 83 rows and 11 variables -============= ===================================== -Column Description -============= ===================================== -name common name -genus -vore carnivore, omnivore or herbivore? -order -conservation the conservation status of the animal -sleep_total total amount of sleep, in hours -sleep_rem rem sleep, in hours -sleep_cycle length of sleep cycle, in hours -awake amount of time spent awake, in hours -brainwt brain weight in kilograms -bodywt body weight in kilograms -============= ===================================== - -.. rubric:: Details +| Column | Description | +|--------------|---------------------------------------| +| name genus | common name | +| vore order | carnivore, omnivore or herbivore? | +| conservation | the conservation status of the animal | +| sleep_total | total amount of sleep, in hours | +| sleep_rem | rem sleep, in hours | +| sleep_cycle | length of sleep cycle, in hours | +| awake | amount of time spent awake, in hours | +| brainwt | brain weight in kilograms | +| bodywt | body weight in kilograms | + +**Details** Additional variables order, conservation status and vore were added from wikipedia. diff --git a/plotnine/doctools.py b/plotnine/doctools.py index 2a0e71523..bd08218f7 100644 --- a/plotnine/doctools.py +++ b/plotnine/doctools.py @@ -6,8 +6,6 @@ from functools import lru_cache from textwrap import dedent, indent, wrap -import numpy as np - if typing.TYPE_CHECKING: from typing import Any, Type, TypeVar @@ -48,37 +46,36 @@ {signature} -Only the ``data`` and ``mapping`` can be positional, the rest must -be keyword arguments. ``**kwargs`` can be aesthetics (or parameters) -used by the ``stat``. +Only the `data` and `mapping` can be positional, the rest must +be keyword arguments. `**kwargs` can be aesthetics (or parameters) +used by the `stat`. """ AESTHETICS_TABLE_TPL = """ {table} -The **bold** aesthetics are required. -""" +The **bold** aesthetics are required.""" STAT_SIGNATURE_TPL = """ **Usage** {signature} -Only the ``mapping`` and ``data`` can be positional, the rest must -be keyword arguments. ``**kwargs`` can be aesthetics (or parameters) -used by the ``geom``. +Only the `mapping` and `data` can be positional, the rest must +be keyword arguments. `**kwargs` can be aesthetics (or parameters) +used by the `geom`. """ common_params_doc = { "mapping": """\ Aesthetic mappings created with [](`~plotnine.mapping.aes`). If specified \ -and :py:`inherit.aes=True`, it is combined with the default mapping for \ +and `inherit_aes=True`{.py}, it is combined with the default mapping for \ the plot. You must supply mapping if there is no plot mapping.""", "data": """\ -The data to be displayed in this layer. If :py:`None`, the data from \ -from the :py:`ggplot()` call is used. If specified, it overrides the \ -data from the :py:`ggplot()` call.""", +The data to be displayed in this layer. If `None`{.py}, the data from \ +from the `ggplot()`{.py} call is used. If specified, it overrides the \ +data from the `ggplot()`{.py} call.""", "stat": """\ The statistical transformation to use on the data for this layer. \ If it is a string, it must be the registered and known to Plotnine.""", @@ -86,54 +83,54 @@ Position adjustment. If it is a string, it must be registered and \ known to Plotnine.""", "na_rm": """\ -If :py:`False`, removes missing values with a warning. If :py:`True` \ +If `False`{.py}, removes missing values with a warning. If `True`{.py} \ silently removes missing values.""", "inherit_aes": """\ -If :py:`False`, overrides the default aesthetics.""", +If `False`{.py}, overrides the default aesthetics.""", "show_legend": """\ -Whether this layer should be included in the legends. :py:`None` the \ +Whether this layer should be included in the legends. `None`{.py} the \ default, includes any aesthetics that are mapped. If a :class:`bool`, \ -:py:`False` never includes and :py:`True` always includes. A \ +`False`{.py} never includes and `True`{.py} always includes. A \ :class:`dict` can be used to *exclude* specific aesthetis of the layer \ -from showing in the legend. e.g :py:`show_legend={'color': False}`, \ +from showing in the legend. e.g `show_legend={'color': False}`{.py}, \ any other aesthetic are included by default.""", "raster": """\ -If ``True``, draw onto this layer a raster (bitmap) object even if\ +If `True`, draw onto this layer a raster (bitmap) object even if\ the final image is in vector format.""", } -GEOM_PARAMS_TPL = """\ -mapping : aes, optional +GEOM_PARAMS_TPL = """ +mapping : aes, default=None {mapping} {_aesthetics_doc} -data : dataframe, optional +data : dataframe, default=None {data} -stat : str or stat, optional (default: {default_stat}) +stat : str or stat, default={default_stat} {stat} -position : str or position, optional (default: {default_position}) +position : str or position, default={default_position} {position} -na_rm : bool, optional (default: {default_na_rm}) +na_rm : bool, default={default_na_rm} {na_rm} -inherit_aes : bool, optional (default: {default_inherit_aes}) +inherit_aes : bool, default={default_inherit_aes} {inherit_aes} -show_legend : bool or dict, optional (default: None) +show_legend : bool or dict, default=None {show_legend} -raster : bool, optional (default: {default_raster}) +raster : bool, default={default_raster} {raster} """ -STAT_PARAMS_TPL = """\ -mapping : aes, optional +STAT_PARAMS_TPL = """ +mapping : aes, default=None {mapping} {_aesthetics_doc} -data : dataframe, optional +data : dataframe, default=None {data} -geom : str or geom, optional (default: {default_geom}) +geom : str or geom, default={default_geom} {stat} -position : str or position, optional (default: {default_position}) +position : str or position, default={default_position} {position} -na_rm : bool, optional (default: {default_na_rm}) +na_rm : bool, default={default_na_rm} {na_rm} """ @@ -169,42 +166,25 @@ def dict_to_table(header: tuple[str, str], contents: dict[str, str]) -> str: ========= ========= Aesthetic Default Value ========= ========= - alpha :py:`1` - color :py:`'blue'` - fill :py:`None` + alpha `1` + color `'blue'` + fill `None` ========= ========= """ from tabulate import tabulate if GENERATING_QUARTODOC: - return tabulate( - list(contents.items()), headers=header, tablefmt="unsafehtml" - ) - - def to_text(row: tuple[str, str]) -> str: - name, value = row - m = max_col1_size + 1 - len(name) - spacing = " " * m - return "".join([name, spacing, value]) - - def longest_value(row: tuple[str, str]) -> int: - return max(len(value) for value in row) - - rows = [] - for name, value in contents.items(): - # code highlighting - if value != "": - if isinstance(value, str): - value = f"'{value}'" - value = f":py:`{value}`" - rows.append((name, value)) - - n = max(longest_value(row) for row in [header] + rows) - hborder = "=" * n, "=" * n - rows = [hborder, header, hborder] + rows + [hborder] - max_col1_size = np.max([len(col1) for col1, _ in rows]) - table = "\n".join([to_text(row) for row in rows]) - return table + tablefmt = "unsafehtml" + rows = [] + for name, value in contents.items(): + if value != "": + value = f"`{repr(value)}`" "{.py}" + rows.append((name, value)) + else: + tablefmt = "grid" + rows = list(contents.items()) + + return tabulate(rows, headers=header, tablefmt=tablefmt) def make_signature( @@ -339,8 +319,8 @@ def parameters_str_to_dict(param_section: str) -> dict[str, str]: d : dict Dictionary of the parameters in the order that they are described in the parameters section. The dict - is of the form ``{param: all_parameter_text}``. - You can reconstruct the ``param_section`` from the + is of the form `{param: all_parameter_text}`. + You can reconstruct the `param_section` from the keys of the dictionary. See Also @@ -387,7 +367,7 @@ def parameters_dict_to_str(d: dict[str, str]) -> str: return "\n".join(d.values()) -def qualified_name(s: str | type | object, prefix: str) -> str: +def default_class_name(s: str | type | object) -> str: """ Return the qualified name of s @@ -395,22 +375,15 @@ def qualified_name(s: str | type | object, prefix: str) -> str: Examples -------- - >>> qualified_name('bin', 'stat_') - '~plotnine.stats.stat_bin' - >>> qualified_name('point', 'geom_') - '~plotnine.geoms.geom_point' - >>> qualified_name('stack', 'position_') - '~plotnine.positions.position_' + >>> qualified_name('stat_bin') + 'stat_bin' + >>> qualified_name(stat_bin) + 'stat_bin' + >>> qualified_name(stat_bin()) + 'stat_bin' """ - lookup = { - "stat_": "~plotnine.stats.stat_", - "geom_": "~plotnine.geoms.geom_", - "position_": "~plotnine.positions.position_", - } if isinstance(s, str): - if not s.startswith(prefix) and prefix in lookup: - pre = lookup[prefix] - s = f"{pre}{s}" + return s elif isinstance(s, type): s = s.__name__ else: @@ -447,21 +420,21 @@ def document_geom(geom: type[Geom]) -> type[Geom]: table = dict_to_table(("Aesthetic", "Default value"), contents) aesthetics_table = AESTHETICS_TABLE_TPL.format(table=table) - tpl = dedent(geom._aesthetics_doc.lstrip("\n")) + tpl = dedent(geom._aesthetics_doc.strip("\n")) aesthetics_doc = tpl.format(aesthetics_table=aesthetics_table) aesthetics_doc = indent(aesthetics_doc, " " * 4) # common_parameters d = geom.DEFAULT_PARAMS common_parameters = GEOM_PARAMS_TPL.format( - default_stat=qualified_name(d["stat"], "stat_"), - default_position=qualified_name(d["position"], "position_"), + default_stat=default_class_name(d["stat"]), + default_position=default_class_name(d["position"]), default_na_rm=d["na_rm"], default_inherit_aes=d.get("inherit_aes", True), default_raster=d.get("raster", False), _aesthetics_doc=aesthetics_doc, **common_params_doc, - ) + ).strip() docstring = docstring.replace("{usage}", usage) docstring = docstring.replace("{common_parameters}", common_parameters) @@ -494,19 +467,19 @@ def document_stat(stat: type[Stat]) -> type[Stat]: contents.update(sorted(stat.DEFAULT_AES.items())) table = dict_to_table(("Aesthetic", "Default value"), contents) aesthetics_table = AESTHETICS_TABLE_TPL.format(table=table) - tpl = dedent(stat._aesthetics_doc.lstrip("\n")) - aesthetics_doc = tpl.format(aesthetics_table=aesthetics_table) + tpl = dedent(stat._aesthetics_doc.strip("\n")) + aesthetics_doc = tpl.replace("{aesthetics_table}", aesthetics_table) aesthetics_doc = indent(aesthetics_doc, " " * 4) # common_parameters d = stat.DEFAULT_PARAMS common_parameters = STAT_PARAMS_TPL.format( - default_geom=qualified_name(d["geom"], "geom_"), - default_position=qualified_name(d["position"], "position_"), + default_geom=default_class_name(d["geom"]), + default_position=default_class_name(d["position"]), default_na_rm=d["na_rm"], _aesthetics_doc=aesthetics_doc, **common_params_doc, - ) + ).strip() docstring = docstring.replace("{usage}", usage) docstring = docstring.replace("{common_parameters}", common_parameters) diff --git a/plotnine/facets/facet.py b/plotnine/facets/facet.py index bda3b0e6b..b9e3931f2 100644 --- a/plotnine/facets/facet.py +++ b/plotnine/facets/facet.py @@ -40,30 +40,31 @@ class facet: Parameters ---------- - scales : str in ``['fixed', 'free', 'free_x', 'free_y']`` - Whether ``x`` or ``y`` scales should be allowed (free) - to vary according to the data along the rows or the - columns. Default is ``'fixed'``. + scales : "fixed", "free", "free_x", "free_y", default="fixed" + Whether `x` or `y` scales should be allowed (free) + to vary according to the data on each of the panel. shrink : bool Whether to shrink the scales to the output of the - statistics instead of the raw data. Default is ``True``. - labeller : str | function - How to label the facets. If it is a ``str``, it should - be one of ``'label_value'`` ``'label_both'`` or - ``'label_context'``. Default is ``'label_value'`` - as_table : bool - If ``True``, the facets are laid out like a table with - the highest values at the bottom-right. If ``False`` + statistics instead of the raw data. Default is `True`. + shrink : bool, default=True + Whether to shrink the scales to the output of the + statistics instead of the raw data. + labeller : str, callable, default="label_value" + How to label the facets. A string value if it should be + one of `["label_value", "label_both", "label_context"]`{.py}. + as_table : bool, default=True + If `True`, the facets are laid out like a table with + the highest values at the bottom-right. If `False` the facets are laid out like a plot with the highest - value a the top-right. Default it ``True``. - drop : bool - If ``True``, all factor levels not used in the data - will automatically be dropped. If ``False``, all + value a the top-right + drop : bool, default=True + If `True`, all factor levels not used in the data + will automatically be dropped. If `False`, all factor levels will be shown, regardless of whether - or not they appear in the data. Default is ``True``. - dir : str in ``['h', 'v']`` - Direction in which to layout the panels. ``h`` for - horizontal and ``v`` for vertical. + or not they appear in the data. + dir : "h", "v", default="h" + Direction in which to layout the panels. `h` for + horizontal and `v` for vertical. """ #: number of columns diff --git a/plotnine/facets/facet_grid.py b/plotnine/facets/facet_grid.py index 6b52d0eb3..f84bd776f 100644 --- a/plotnine/facets/facet_grid.py +++ b/plotnine/facets/facet_grid.py @@ -37,28 +37,32 @@ class facet_grid(facet): must of size two, the elements of which must be strings or lists. If string formula is not processed as you may expect, use tuple/list. For example, the - follow two specifications are equivalent:: + follow two specifications are equivalent: - 'func(var4) ~ func(var1+var3) + func(var2)' - ['func(var4)', ('func(var1+var3)', 'func(var2)')] + ```python + "func(var4) ~ func(var1+var3) + func(var2)" - There may be cases where you cannot use a - use a pure string formula, e.g.:: + ["func(var4)", ("func(var1+var3)", "func(var2)")] + ``` - ['var4', ('var1+var3', 'var2')] + There may be cases where you cannot use a + use a pure string formula, e.g. + ```python + ['var4', ('var1+var3', 'var2')] + ``` margins : bool | list[str] variable names to compute margins for. True will compute all possible margins. space : str | dict - Control the size of the ``x`` or ``y`` sides of the panels. - The size also depends to the ``scales`` parameter. + Control the size of the `x` or `y` sides of the panels. + The size also depends to the `scales` parameter. If a string, it should be one of ``['fixed', 'free', 'free_x', 'free_y']``. Currently, only the ``'fixed'`` option is supported. - Alternatively if a ``dict``, it indicates the relative facet + Alternatively if a `dict`, it indicates the relative facet size ratios such as:: {'x': [1, 2], 'y': [3, 1, 1]} @@ -71,23 +75,22 @@ class facet_grid(facet): Note that the number of dimensions in the list must equal the number of facets that will be produced. - shrink : bool + shrink : bool, default=True Whether to shrink the scales to the output of the - statistics instead of the raw data. Default is ``True``. - labeller : str | function - How to label the facets. If it is a ``str``, it should - be one of ``'label_value'`` ``'label_both'`` or - ``'label_context'``. Default is ``'label_value'`` - as_table : bool - If ``True``, the facets are laid out like a table with - the highest values at the bottom-right. If ``False`` + statistics instead of the raw data. + labeller : str, callable, default="label_value" + How to label the facets. A string value if it should be + one of `["label_value", "label_both", "label_context"]`{.py}. + as_table : bool, default=True + If `True`, the facets are laid out like a table with + the highest values at the bottom-right. If `False` the facets are laid out like a plot with the highest - value a the top-right. Default it ``True``. - drop : bool - If ``True``, all factor levels not used in the data - will automatically be dropped. If ``False``, all + value a the top-right + drop : bool, default=True + If `True`, all factor levels not used in the data + will automatically be dropped. If `False`, all factor levels will be shown, regardless of whether - or not they appear in the data. Default is ``True``. + or not they appear in the data. """ rows: list[str] diff --git a/plotnine/facets/facet_null.py b/plotnine/facets/facet_null.py index 2e2bfe522..8620d3955 100644 --- a/plotnine/facets/facet_null.py +++ b/plotnine/facets/facet_null.py @@ -14,9 +14,9 @@ class facet_null(facet): Parameters ---------- - shrink : bool + shrink : bool, default=True Whether to shrink the scales to the output of the - statistics instead of the raw data. Default is ``True``. + statistics instead of the raw data. """ def __init__(self, shrink: bool = True): diff --git a/plotnine/facets/facet_wrap.py b/plotnine/facets/facet_wrap.py index ee66714da..59d72eca1 100644 --- a/plotnine/facets/facet_wrap.py +++ b/plotnine/facets/facet_wrap.py @@ -31,38 +31,36 @@ class facet_wrap(facet): Parameters ---------- - facets : formula | tuple | list + facets : str| tuple Variables to groupby and plot on different panels. - If a formula is used it should be right sided, - e.g ``'~ a + b'``, ``('a', 'b')`` - nrow : int, optional + If a string formula is used it should be right sided, + e.g `"~ a + b"`, `("a", "b")` + nrow : int, default=None Number of rows - ncol : int, optional + ncol : int, default=None Number of columns - scales : str in ``['fixed', 'free', 'free_x', 'free_y']`` - Whether ``x`` or ``y`` scales should be allowed (free) + scales : "fixed", "free", "free_x", "free_y", default="fixed" + Whether `x` or `y` scales should be allowed (free) to vary according to the data on each of the panel. - Default is ``'fixed'``. - shrink : bool + shrink : bool, default=True Whether to shrink the scales to the output of the - statistics instead of the raw data. Default is ``True``. - labeller : str | function - How to label the facets. If it is a ``str``, it should - be one of ``'label_value'`` ``'label_both'`` or - ``'label_context'``. Default is ``'label_value'`` - as_table : bool - If ``True``, the facets are laid out like a table with - the highest values at the bottom-right. If ``False`` + statistics instead of the raw data. + labeller : str, callable, default="label_value" + How to label the facets. A string value if it should be + one of `["label_value", "label_both", "label_context"]`{.py}. + as_table : bool, default=True + If `True`, the facets are laid out like a table with + the highest values at the bottom-right. If `False` the facets are laid out like a plot with the highest - value a the top-right. Default it ``True``. - drop : bool - If ``True``, all factor levels not used in the data - will automatically be dropped. If ``False``, all + value a the top-right + drop : bool, default=True + If `True`, all factor levels not used in the data + will automatically be dropped. If `False`, all factor levels will be shown, regardless of whether - or not they appear in the data. Default is ``True``. - dir : str in ``['h', 'v']`` - Direction in which to layout the panels. ``h`` for - horizontal and ``v`` for vertical. + or not they appear in the data. + dir : "h", "v", default="h" + Direction in which to layout the panels. `h` for + horizontal and `v` for vertical. """ def __init__( diff --git a/plotnine/facets/labelling.py b/plotnine/facets/labelling.py index bf704c093..18d6e7a4f 100644 --- a/plotnine/facets/labelling.py +++ b/plotnine/facets/labelling.py @@ -153,16 +153,15 @@ class labeller: Parameters ---------- - rows : str | function | None + rows : str, callable How to label the rows - cols : str | function | None + cols : str, callable How to label the columns multi_line : bool Whether to place each variable on a separate line - default : function | str - Fallback labelling function. If it is a string, - it should be the name of one the labelling - functions provided by plotnine. + default : str, callable + Fallback labelling function. If it is a string, it should be + one of `["label_value", "label_both", "label_context"]`{.py}. kwargs : dict {variable name : function | string} pairs for renaming variables. A function to rename the variable diff --git a/plotnine/facets/layout.py b/plotnine/facets/layout.py index 14fb18e99..ff5526e44 100644 --- a/plotnine/facets/layout.py +++ b/plotnine/facets/layout.py @@ -230,8 +230,8 @@ def xlabel(self, labels: labels_view) -> str: Parameters ---------- labels : labels_view - Labels as specified by the user through the ``labs`` or - ``xlab`` calls. + Labels as specified by the user through the `labs` or + `xlab` calls. Returns ------- @@ -251,8 +251,8 @@ def ylabel(self, labels: labels_view) -> str: Parameters ---------- labels : labels_view - Labels as specified by the user through the ``labs`` or - ``ylab`` calls. + Labels as specified by the user through the `labs` or + `ylab` calls. Returns ------- @@ -272,8 +272,8 @@ def set_xy_labels(self, labels: labels_view) -> labels_view: Parameters ---------- labels : labels_view - Labels as specified by the user through the ``labs`` or - ``ylab`` calls. + Labels as specified by the user through the `labs` or + `ylab` calls. Returns ------- diff --git a/plotnine/geoms/annotate.py b/plotnine/geoms/annotate.py index 0a6dc9628..5416ae442 100644 --- a/plotnine/geoms/annotate.py +++ b/plotnine/geoms/annotate.py @@ -49,8 +49,8 @@ class annotate: Notes ----- - The positioning aethetics ``x, y, xmin, ymin, xmax, ymax, xend, yend, - xintercept, yintercept`` depend on which `geom` is used. + The positioning aethetics `x, y, xmin, ymin, xmax, ymax, xend, yend, + xintercept, yintercept` depend on which `geom` is used. You should choose or ignore accordingly. diff --git a/plotnine/geoms/annotation_logticks.py b/plotnine/geoms/annotation_logticks.py index 3d2637567..6604db340 100644 --- a/plotnine/geoms/annotation_logticks.py +++ b/plotnine/geoms/annotation_logticks.py @@ -79,15 +79,15 @@ def _check_log_scale( ---------- base : float or None Base of the logarithm in which the ticks will be - calculated. If ``None``, the base of the log transform + calculated. If `None`, the base of the log transform the scale will be used. sides : str (default: bl) Sides onto which to draw the marks. Any combination - chosen from the characters ``btlr``, for *bottom*, *top*, - *left* or *right* side marks. If ``coord_flip()`` is used, + chosen from the characters `btlr`, for *bottom*, *top*, + *left* or *right* side marks. If `coord_flip()` is used, these are the sides *before* the flip. panel_params : panel_view - ``x`` and ``y`` view scale values. + `x` and `y` view scale values. coord : coord Coordinate (e.g. coord_cartesian) system of the geom. @@ -253,8 +253,8 @@ class annotation_logticks(annotate): ---------- sides : str (default: bl) Sides onto which to draw the marks. Any combination - chosen from the characters ``btlr``, for *bottom*, *top*, - *left* or *right* side marks. If ``coord_flip()`` is used, + chosen from the characters `btlr`, for *bottom*, *top*, + *left* or *right* side marks. If `coord_flip()` is used, these are the sides *after* the flip. alpha : float (default: 1) Transparency of the ticks @@ -269,7 +269,7 @@ class annotation_logticks(annotate): ticks relative to panel size base : float (default: None) Base of the logarithm in which the ticks will be - calculated. If ``None``, the base used to log transform + calculated. If `None`, the base used to log transform the scale will be used. """ diff --git a/plotnine/geoms/geom.py b/plotnine/geoms/geom.py index 529f20f5a..24e69b93b 100644 --- a/plotnine/geoms/geom.py +++ b/plotnine/geoms/geom.py @@ -58,7 +58,7 @@ class geom(metaclass=Registry): #: geom/layer specific dataframe data: DataLike - #: mappings i.e. :py:`aes(x='col1', fill='col2')` + #: mappings i.e. `aes(x='col1', fill='col2')`{.py} mapping: Aes aes_params: dict[str, Any] = {} # setting of aesthetic @@ -183,13 +183,13 @@ def setup_data(self, data: pd.DataFrame) -> pd.DataFrame: drawing. The base class method does nothing, geoms can override this method for two reasons: - 1. The ``stat`` does not create all the aesthetics (usually - position aesthetics) required for drawing the ``geom``, + 1. The `stat` does not create all the aesthetics (usually + position aesthetics) required for drawing the `geom`, but those aesthetics can be computed from the available data. For example [](`~plotnine.geoms.geom_boxplot`) and [](`~plotnine.geoms.geom_violin`). - 2. The ``geom`` inherits from another ``geom`` (superclass) which + 2. The `geom` inherits from another `geom` (superclass) which does the drawing and the superclass requires certain aesthetics to be present in the data. For example [](`~plotnine.geoms.geom_tile`) and diff --git a/plotnine/geoms/geom_bar.py b/plotnine/geoms/geom_bar.py index 27af80960..a72ed2dbc 100644 --- a/plotnine/geoms/geom_bar.py +++ b/plotnine/geoms/geom_bar.py @@ -21,7 +21,7 @@ class geom_bar(geom_rect): ---------- {common_parameters} width : float, optional (default None) - Bar width. If :py:`None`, the width is set to + Bar width. If `None`{.py}, the width is set to `90%` of the resolution of the data. See Also diff --git a/plotnine/geoms/geom_boxplot.py b/plotnine/geoms/geom_boxplot.py index 5ea174986..304898c32 100644 --- a/plotnine/geoms/geom_boxplot.py +++ b/plotnine/geoms/geom_boxplot.py @@ -47,29 +47,29 @@ class geom_boxplot(geom): Parameters ---------- {common_parameters} - width : float, optional (default None) - Box width. If :py:`None`, the width is set to + width : float, default=None + Box width. If `None`{.py}, the width is set to `90%` of the resolution of the data. Note that if the stat has a width parameter, that takes precedence over this one. - outlier_alpha : float, optional (default: 1) + outlier_alpha : float, default=1 Transparency of the outlier points. - outlier_color : str or tuple, optional (default: None) + outlier_color : str, tuple, default=None Color of the outlier points. - outlier_shape : str, optional (default: o) + outlier_shape : str, default="o" Shape of the outlier points. An empty string hides the outliers. - outlier_size : float, optional (default: 1.5) + outlier_size : float, default=1.5 Size of the outlier points. - outlier_stroke : float, optional (default: 0.5) + outlier_stroke : float, default=0.5 Stroke-size of the outlier points. - notch : bool, optional (default: False) + notch : bool, default=False Whether the boxes should have a notch. - varwidth : bool, optional (default: False) - If :py:`True`, boxes are drawn with widths proportional to + varwidth : bool, default=False + If `True`{.py}, boxes are drawn with widths proportional to the square-roots of the number of observations in the groups. - notchwidth : float, optional (default: 0.5) + notchwidth : float, default=0.5 Width of notch relative to the body width. - fatten : float, optional (default: 2) + fatten : float, default=2 A multiplicative factor used to increase the size of the middle bar across the box. """ diff --git a/plotnine/geoms/geom_col.py b/plotnine/geoms/geom_col.py index 96f9e263b..f8629e0d9 100644 --- a/plotnine/geoms/geom_col.py +++ b/plotnine/geoms/geom_col.py @@ -17,8 +17,8 @@ class geom_col(geom_bar): Parameters ---------- {common_parameters} - width : float, (default: None) - Bar width. If :py:`None`, the width is set to + width : float, default=None + Bar width. If `None`{.py}, the width is set to `90%` of the resolution of the data. See Also diff --git a/plotnine/geoms/geom_crossbar.py b/plotnine/geoms/geom_crossbar.py index e26bad58a..06acc8031 100644 --- a/plotnine/geoms/geom_crossbar.py +++ b/plotnine/geoms/geom_crossbar.py @@ -32,10 +32,9 @@ class geom_crossbar(geom): Parameters ---------- {common_parameters} - width : float or None, optional (default: 0.5) - Box width. If :py:`None`, the width is set to - `90%` of the resolution of the data. - fatten : float, optional (default: 2) + width : float, default=0.5 + Box width as a fraction of the resolution of the data. + fatten : float, default=2 A multiplicative factor used to increase the size of the middle bar across the box. """ diff --git a/plotnine/geoms/geom_dotplot.py b/plotnine/geoms/geom_dotplot.py index dca3d3a35..ff44b5cf4 100644 --- a/plotnine/geoms/geom_dotplot.py +++ b/plotnine/geoms/geom_dotplot.py @@ -28,24 +28,24 @@ class geom_dotplot(geom): Parameters ---------- - {common_parameters} - stackdir : str (default: up) + {commonparameters} + stackdir : str, default="up" Direction in which to stack the dots. Options are - :py:`['up', 'down', 'center', 'centerwhole']` - stackratio : float (default: 1) + `['up', 'down', 'center', 'centerwhole']`{.py} + stackratio : float, default=1 How close to stack the dots. If value is less than 1, the dots overlap, if greater than 1 they are spaced. - dotsize : float (default: 1) - Diameter of dots relative to ``binwidth``. - stackgroups : bool (default: False) - If :py:`True`, the dots are stacked across groups. + dotsize : float, default=1 + Diameter of dots relative to `binwidth`. + stackgroups : bool, default=False + If `True`{.py}, the dots are stacked across groups. See Also -------- - plotnine.stats.stat_bindot + plotnine.stats.statbindot """ - DEFAULT_AES = {"alpha": 1, "color": "black", "fill": "black"} + DEFAULTAES = {"alpha": 1, "color": "black", "fill": "black"} REQUIRED_AES = {"x", "y"} NON_MISSING_AES = {"size", "shape"} DEFAULT_PARAMS = { diff --git a/plotnine/geoms/geom_errorbar.py b/plotnine/geoms/geom_errorbar.py index 7763d9c47..d6d0b5718 100644 --- a/plotnine/geoms/geom_errorbar.py +++ b/plotnine/geoms/geom_errorbar.py @@ -28,9 +28,8 @@ class geom_errorbar(geom): Parameters ---------- {common_parameters} - width : float or None, optional (default: 0.5) - Bar width. If :py:`None`, the width is set to - `90%` of the resolution of the data. + width : float, default=0.5 + Bar width as a fraction of the resolution of the data. """ DEFAULT_AES = { diff --git a/plotnine/geoms/geom_errorbarh.py b/plotnine/geoms/geom_errorbarh.py index 1f272fb7f..6a4ffbbfd 100644 --- a/plotnine/geoms/geom_errorbarh.py +++ b/plotnine/geoms/geom_errorbarh.py @@ -28,9 +28,8 @@ class geom_errorbarh(geom): Parameters ---------- {common_parameters} - height : float or None, optional (default: 0.5) - Bar height. If :py:`None`, the height is set to - `90%` of the resolution of the data. + height : float, default=0.5 + Bar height as a fraction of the resolution of the data. """ DEFAULT_AES = { diff --git a/plotnine/geoms/geom_jitter.py b/plotnine/geoms/geom_jitter.py index 7ea35a57f..1dd25e037 100644 --- a/plotnine/geoms/geom_jitter.py +++ b/plotnine/geoms/geom_jitter.py @@ -23,16 +23,16 @@ class geom_jitter(geom_point): Parameters ---------- {common_parameters} - width : float, optional + width : float, default=None Proportion to jitter in horizontal direction. The default value is that from [](`~plotnine.positions.position_jitter`) - height : float, optional + height : float, default=None Proportion to jitter in vertical direction. The default value is that from [](`~plotnine.positions.position_jitter`). - random_state : int or ~numpy.random.RandomState, optional - Seed or Random number generator to use. If ``None``, then + random_state : int, ~numpy.random.RandomState, default=None + Seed or Random number generator to use. If `None`, then numpy global generator :class:`numpy.random` is used. See Also diff --git a/plotnine/geoms/geom_label.py b/plotnine/geoms/geom_label.py index e0bcbf605..0eb6e0661 100644 --- a/plotnine/geoms/geom_label.py +++ b/plotnine/geoms/geom_label.py @@ -45,29 +45,30 @@ class geom_label(geom_text): Parameters ---------- {common_parameters} - boxstyle : str, optional (default: round) - Options are:: - - 'circle' - 'darrow' - 'larrow' - 'rarrow' - 'round ' - 'round4' - 'roundtooth' - 'sawtooth' - 'square' - boxcolor: None, str or rgba tuple (default: None) + boxstyle : str, default="round" + Options are: + ```python + 'circle' + 'darrow' + 'larrow' + 'rarrow' + 'round ' + 'round4' + 'roundtooth' + 'sawtooth' + 'square' + ```` + boxcolor: strr, rgba tuple, default=None Color of box around the text. If None, the color is the same as the text. - label_padding : float, optional (default: 0.25) + label_padding : float, default=0.25 Amount of padding - label_r : float, optional (default: 0.25) + label_r : float, default=0.25 Rounding radius of corners. - label_size : float, optional (default: 0.7) + label_size : float, default=0.7 Linewidth of the label boundary. - tooth_size : float, optional (default: None) - Size of the ``roundtooth`` or ``sawtooth`` if they + tooth_size : float, default=None + Size of the `roundtooth` or `sawtooth` if they are the chosen *boxstyle*. The default depends on Matplotlib diff --git a/plotnine/geoms/geom_map.py b/plotnine/geoms/geom_map.py index 56ad84e1a..989d6867e 100644 --- a/plotnine/geoms/geom_map.py +++ b/plotnine/geoms/geom_map.py @@ -46,7 +46,7 @@ class geom_map(geom): Notes ----- This geom is best suited for plotting a shapefile read into - geopandas dataframe. The dataframe should have a ``geometry`` + geopandas dataframe. The dataframe should have a `geometry` column. """ diff --git a/plotnine/geoms/geom_path.py b/plotnine/geoms/geom_path.py index 8d4d35c78..55b6594c3 100644 --- a/plotnine/geoms/geom_path.py +++ b/plotnine/geoms/geom_path.py @@ -33,13 +33,11 @@ class geom_path(geom): Parameters ---------- {common_parameters} - lineend : str (default: butt) - Line end style, of of *butt*, *round* or *projecting.* - This option is applied for solid linetypes. - linejoin : str (default: round) - Line join style, one of *round*, *miter* or *bevel*. - This option is applied for solid linetypes. - arrow : plotnine.geoms.geom_path.arrow (default: None) + lineend : "butt", "round", "projecting", default="butt" + Line end style. This option is applied for solid linetypes. + linejoin : "round", "miter", "bevel", default="round" + Line join style. This option is applied for solid linetypes. + arrow : ~plotnine.geoms.geom_path.arrow, default=None Arrow specification. Default is no arrow. See Also @@ -225,10 +223,10 @@ class arrow: single edge. length : int | float of the edge in "inches" - ends : str in ``['last', 'first', 'both']`` + ends : "last", "first", "both" At which end of the line to draw the arrowhead - type : str in ``['open', 'closed']`` + type : "open", "closed" When it is closed, it is also filled """ diff --git a/plotnine/geoms/geom_pointrange.py b/plotnine/geoms/geom_pointrange.py index 9e2abcd89..88030141f 100644 --- a/plotnine/geoms/geom_pointrange.py +++ b/plotnine/geoms/geom_pointrange.py @@ -27,7 +27,7 @@ class geom_pointrange(geom): Parameters ---------- {common_parameters} - fatten : float, optional (default: 2) + fatten : float, default=2 A multiplicative factor used to increase the size of the point along the line-range. """ diff --git a/plotnine/geoms/geom_polygon.py b/plotnine/geoms/geom_polygon.py index 3f792d36c..b139a79d8 100644 --- a/plotnine/geoms/geom_polygon.py +++ b/plotnine/geoms/geom_polygon.py @@ -30,7 +30,7 @@ class geom_polygon(geom): Notes ----- - All paths in the same ``group`` aesthetic value make up a polygon. + All paths in the same `group` aesthetic value make up a polygon. """ DEFAULT_AES = { diff --git a/plotnine/geoms/geom_quantile.py b/plotnine/geoms/geom_quantile.py index ba9544aa4..20aa253e1 100644 --- a/plotnine/geoms/geom_quantile.py +++ b/plotnine/geoms/geom_quantile.py @@ -12,12 +12,10 @@ class geom_quantile(geom_path): Parameters ---------- {common_parameters} - lineend : str (default: butt) - Line end style, of of *butt*, *round* or *projecting.* - This option is applied for solid linetypes. - linejoin : str (default: round) - Line join style, one of *round*, *miter* or *bevel*. - This option is applied for solid linetypes. + lineend : "butt", "round", "projecting", default="butt" + Line end style. This option is applied for solid linetypes. + linejoin : "round", "miter", "bevel", default="round" + Line join style. This option is applied for solid linetypes. """ DEFAULT_AES = { diff --git a/plotnine/geoms/geom_raster.py b/plotnine/geoms/geom_raster.py index f4a2886b7..864ee2e5d 100644 --- a/plotnine/geoms/geom_raster.py +++ b/plotnine/geoms/geom_raster.py @@ -32,26 +32,41 @@ class geom_raster(geom): ---------- {common_parameters} - hjust : float (default: 0.5) - Horizontal justification for the rectangle at point ``x``. + hjust : float, default=0.5 + Horizontal justification for the rectangle at point `x`. Default is 0.5, which centers the rectangle horizontally. - Must be in the range ``[0, 1]``. - vjust : float (default: 0.5) - Vertical justification for the rectangle at point ``y`` + Must be in the range `[0, 1]`. + vjust : float, default=0.5 + Vertical justification for the rectangle at point `y` Default is 0.5, which centers the rectangle vertically. - Must be in the range ``[0, 1]``. - interpolation : str | None (default: None) + Must be in the range `[0, 1]`. + interpolation : str, default=None How to calculate values between the center points of - adjacent rectangles. The default is :py:`None` not to + adjacent rectangles. The default is `None`{.py} not to interpolate. Allowed values are: - :py:`'none', 'antialiased', 'nearest', 'bilinear', 'bicubic',` - :py:`'spline16', 'spline36', 'hanning', 'hamming', 'hermite',` - :py:`'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel',` - :py:`'mitchell', 'sinc', 'lanczos', 'blackman'` - - filterrad : float, (default: 4.0) + ```python + "antialiased" + "nearest" + "bilinear" + "bicubic" + "spline16" + "spline36" + "hanning" + "hamming" + "hermite" + "kaiser" + "quadric" + "catrom" + "gaussian" + "bessel" + "mitchell" + "sinc" + "lanczos" + "blackman" + ``` + filterrad : float, default=4.0 The filter radius for filters that have a radius parameter, i.e. - when interpolation is one of: *'sinc', 'lanczos' or 'blackman'*. + when interpolation is one of: `sinc`, `lanczos`, `blackman`. Must be a number greater than zero. See Also diff --git a/plotnine/geoms/geom_ribbon.py b/plotnine/geoms/geom_ribbon.py index 2c6a55dbf..dd8b914c4 100644 --- a/plotnine/geoms/geom_ribbon.py +++ b/plotnine/geoms/geom_ribbon.py @@ -30,32 +30,33 @@ class geom_ribbon(geom): Parameters ---------- {common_parameters} - outline_type : 'upper' | 'lower' | 'both' | 'full' + outline_type : "upper", "lower", "both", "full", default="both" How to stroke to outline of the region / area. - * 'upper' - draw only upper bounding line' - * 'lower' - draw only lower bounding line' - * 'both' - draw both upper & lower bounding lines - * 'full' - draw closed polygon around the area. + - `upper` - draw only upper bounding line + - `lower` - draw only lower bounding line + - `both` - draw both upper & lower bounding lines + - `full` - draw closed polygon around the area. """ _aesthetics_doc = """ {aesthetics_table} - .. rubric:: Aesthetics Descriptions + **Aesthetics Descriptions** where - Define where to exclude horizontal regions from being filled. - Regions between any two ``False`` values are skipped. - For sensible demarcation the value used in the *where* predicate - expression should match the ``ymin`` value or expression. i.e. - :: + : Define where to exclude horizontal regions from being filled. + Regions between any two `False` values are skipped. + For sensible demarcation the value used in the *where* predicate + expression should match the `ymin` value or expression. i.e. - aes(ymin=0, ymax='col1', where='col1 > 0') # good - aes(ymin=0, ymax='col1', where='col1 > 10') # bad + ```python + aes(ymin=0, ymax='col1', where='col1 > 0') # good + aes(ymin=0, ymax='col1', where='col1 > 10') # bad - aes(ymin=col2, ymax='col1', where='col1 > col2') # good - aes(ymin=col2, ymax='col1', where='col1 > col3') # bad + aes(ymin=col2, ymax='col1', where='col1 > col2') # good + aes(ymin=col2, ymax='col1', where='col1 > col3') # bad + ``` """ DEFAULT_AES = { "alpha": 1, diff --git a/plotnine/geoms/geom_rug.py b/plotnine/geoms/geom_rug.py index 6a9a99ce7..349ca06d5 100644 --- a/plotnine/geoms/geom_rug.py +++ b/plotnine/geoms/geom_rug.py @@ -29,13 +29,12 @@ class geom_rug(geom): Parameters ---------- {common_parameters} - sides : str (default: bl) + sides : str, default="bl" Sides onto which to draw the marks. Any combination - chosen from the characters ``btlr``, for *bottom*, *top*, + chosen from the characters `"btlr"`, for *bottom*, *top*, *left* or *right* side marks. - length: float - length of marks in fractions of - horizontal/vertical panel size (default 0.03) + length: float, default=0.03 + length of marks in fractions of horizontal/vertical panel size. """ DEFAULT_AES = { diff --git a/plotnine/geoms/geom_segment.py b/plotnine/geoms/geom_segment.py index 441d7a771..1d7cbb484 100644 --- a/plotnine/geoms/geom_segment.py +++ b/plotnine/geoms/geom_segment.py @@ -30,16 +30,14 @@ class geom_segment(geom): Parameters ---------- {common_parameters} - lineend : str (default: butt) - Line end style, of of *butt*, *round* or *projecting.* - This option is applied for solid linetypes. - arrow : plotnine.geoms.geom_path.arrow (default: None) + lineend : "butt", "round", "projecting", default="butt" + Line end style. This option is applied for solid linetypes. + arrow : ~plotnine.geoms.geom_path.arrow, default=None Arrow specification. Default is no arrow. See Also -------- - plotnine.geoms.geom_path.arrow : for adding arrowhead(s) - to segments. + plotnine.geoms.geom_path.arrow : for adding arrowhead(s) to segments. """ DEFAULT_AES = { diff --git a/plotnine/geoms/geom_smooth.py b/plotnine/geoms/geom_smooth.py index 65eff4744..e897cab1f 100644 --- a/plotnine/geoms/geom_smooth.py +++ b/plotnine/geoms/geom_smooth.py @@ -27,7 +27,7 @@ class geom_smooth(geom): Parameters ---------- {common_parameters} - legend_fill_ratio : float (default: 0.5) + legend_fill_ratio : float, default=0.5 How much (vertically) of the legend box should be filled by the color that indicates the confidence intervals. Should be in the range [0, 1]. diff --git a/plotnine/geoms/geom_step.py b/plotnine/geoms/geom_step.py index 96e961c6f..0419bda5f 100644 --- a/plotnine/geoms/geom_step.py +++ b/plotnine/geoms/geom_step.py @@ -28,15 +28,14 @@ class geom_step(geom_path): Parameters ---------- {common_parameters} - direction : str, optional (default: hv) - One of *hv*, *vh* or *mid*, for horizontal-vertical steps, + direction : "hv", "vh", "mid", default="hv" + horizontal-vertical steps, vertical-horizontal steps or steps half-way between adjacent x values. See Also -------- - plotnine.geoms.geom_path : For documentation of extra - parameters. + plotnine.geoms.geom_path : For documentation of extra parameters. """ DEFAULT_PARAMS = { diff --git a/plotnine/geoms/geom_text.py b/plotnine/geoms/geom_text.py index 5346eca81..4694b3279 100644 --- a/plotnine/geoms/geom_text.py +++ b/plotnine/geoms/geom_text.py @@ -34,39 +34,39 @@ class geom_text(geom): Parameters ---------- {common_parameters} - parse : bool (default: False) - If :py:`True`, the labels will be rendered with - `latex `_. - family : str (default: None) + parse : bool, default=False + If `True`{.py}, the labels will be rendered with + [latex](http://matplotlib.org/users/usetex.html). + family : str, default=None Font family. - fontweight : int or str (default: normal) + fontweight : int, str, default="normal" Font weight. - fontstyle : str (default: normal) - Font style. One of *normal*, *italic* or *oblique* - nudge_x : float (default: 0) + fontstyle : "normal", "italic", "oblique", default="normal" + Font style. + nudge_x : float, default=0 Horizontal adjustment to apply to the text - nudge_y : float (default: 0) + nudge_y : float, default=0 Vertical adjustment to apply to the text - adjust_text: dict (default: None) + adjust_text: dict, default=None Parameters to :class:`adjustText.adjust_text` will repel overlapping texts. This parameter takes priority of over - ``nudge_x`` and ``nudge_y``. + `nudge_x` and `nudge_y`. - ``adjust_text`` does not work well when it is used in the + `adjust_text` does not work well when it is used in the first layer of the plot, or if it is the only layer. For more see the documentation at https://github.com/Phlya/adjustText/wiki . - format_string : str (default: None) - If not :py:`None`, then the text is formatted with this + format_string : str, default=None + If not `None`{.py}, then the text is formatted with this string using :meth:`str.format` e.g:: # 2.348 -> "2.35%" geom_text(format_string="{:.2f}%") - path_effects : list (default: None) - If not :py:`None`, then the text will use these effects. - See `path_effects - `_ + path_effects : list, default=None + If not `None`{.py}, then the text will use these effects. + See + [](https://matplotlib.org/tutorials/advanced/patheffects_guide.html) documentation for more details. See Also @@ -80,14 +80,15 @@ class geom_text(geom): _aesthetics_doc = """ {aesthetics_table} - .. rubric:: Aesthetics Descriptions + **Aesthetics Descriptions** ha - Horizontal alignment. One of *left*, *center* or *right.* + + : Horizontal alignment. One of *left*, *center* or *right.* va - Vertical alignment. One of *top*, *center*, *bottom*, *baseline*. + : Vertical alignment. One of *top*, *center*, *bottom*, *baseline*. """ DEFAULT_AES = { "alpha": 1, diff --git a/plotnine/geoms/geom_violin.py b/plotnine/geoms/geom_violin.py index 0ac7eb233..aa18a7690 100644 --- a/plotnine/geoms/geom_violin.py +++ b/plotnine/geoms/geom_violin.py @@ -28,20 +28,19 @@ class geom_violin(geom): Parameters ---------- {common_parameters} - draw_quantiles : float or [float] + draw_quantiles : float, list[float], default=None draw horizontal lines at the given quantiles (0..1) of the density estimate. - style : str, optional (default: 'full') + style : str, default="full" The type of violin plot to draw. The options are: - :: - - 'full' # Regular (2 sided violins) - 'left' # Left-sided half violins - 'right' # Right-sided half violins - 'left-right' # Alternate (left first) half violins by the group - 'right-left' # Alternate (right first) half violins by the group - + ```python + 'full' # Regular (2 sided violins) + 'left' # Left-sided half violins + 'right' # Right-sided half violins + 'left-right' # Alternate (left first) half violins by the group + 'right-left' # Alternate (right first) half violins by the group + ``` """ DEFAULT_AES = { diff --git a/plotnine/ggplot.py b/plotnine/ggplot.py index c3a2cf6f1..dae85cc53 100755 --- a/plotnine/ggplot.py +++ b/plotnine/ggplot.py @@ -636,11 +636,11 @@ def save( DPI to use for raster graphics. If None, defaults to using the `dpi` of theme, if none is set then a `dpi` of 100. limitsize : bool - If ``True`` (the default), ggsave will not save images + If `True` (the default), ggsave will not save images larger than 50x50 inches, to prevent the common error of specifying dimensions in pixels. verbose : bool - If ``True``, print the saving information. + If `True`, print the saving information. kwargs : dict Additional arguments to pass to matplotlib `savefig()`. """ @@ -696,7 +696,7 @@ def save_as_pdf_pages( Path to save plot to (if you just want to set path and not filename). verbose : :py:class:`bool` - If ``True``, print the saving information. + If `True`, print the saving information. kwargs : :py:class:`dict` Additional arguments to pass to :py:meth:`matplotlib.figure.Figure.savefig`. diff --git a/plotnine/guides/guide.py b/plotnine/guides/guide.py index 3162b0656..9b01283f1 100644 --- a/plotnine/guides/guide.py +++ b/plotnine/guides/guide.py @@ -19,49 +19,52 @@ class guide(metaclass=Registry): Parameters ---------- - title : str | None - Title of the guide. If ``None``, title is not shown. + title : str, None + Title of the guide. If `None`, title is not shown. Default is the name of the aesthetic or the name specified using [](`~plotnine.components.labels.lab`) - title_position : str in ``['top', 'bottom', 'left', 'right']`` - Position of title - title_theme : element_text + title_position : str, default="auto" + Position of title. One of + `["top", "bottom", "left", "right"]`{.py} + title_theme : element_text, default=None Control over the title theme. - Default is to use ``legend_title`` in a theme. - title_hjust : float + Default is to use `legend_title` in a theme. + title_hjust : float, default=None Horizontal justification of title text. - title_vjust : float + title_vjust : float, default=None Vertical justification of title text. - title_separation : float + title_separation : float, default=None Separation between the title text and the colorbar. Value is in pixels. - label : bool + label : bool, default=True Whether to show labels - label_position : str in ``['top', 'bottom', 'left', 'right']`` + label_position : str, default="auto" Position of the labels. - The defaults are ``'bottom'`` for a horizontal guide and - '``right``' for a vertical guide. - label_theme : element_text + One of `["top", "bottom", "left", "right"]`{.py}. + The default is "bottom" for a horizontal guide and + "right" for a vertical guide. + label_theme : element_text, default=None Control over the label theme. - Default is to use ``legend_text`` in a theme. - label_hjust : float + Default is to use `legend_text` in a theme. + label_hjust : float, default=None Horizontal justification of label text. - label_vjust : float + label_vjust : float, default=None Vertical justification of label text. - label_separation : float + label_separation : float, default=None Separation between the label text and the colorbar. Value is in pixels. - direction : str in ``['horizontal', 'vertical']`` - Direction of the guide. - default_unit : str - Unit for ``keywidth`` and ``keyheight`` - override_aes : dict + direction : "horizontal", "vertical", default="auto" + Direction of the guide. The default is depends on + [](`~plotnine.themes.themeable.legend_position`). + default_unit : str, default="lines" + Unit for `keywidth` and `keyheight`. + override_aes : dict, default={} Aesthetic parameters of legend key. - reverse : bool + reverse : bool, default=False Whether to reverse the order of the legends. - order : int + order : int, default=0 Order of this guide among multiple guides. - Should be in the range [0, 99]. Default is ``0``. + Should be in the range [0, 99]. Notes ----- @@ -90,7 +93,7 @@ class guide(metaclass=Registry): # general direction: Optional[Literal["horizontal", "vertical"]] = None - default_unit = "line" + default_unit = "lines" override_aes: dict[str, Any] = {} reverse = False order = 0 @@ -165,7 +168,7 @@ def _set_defaults(self, theme: Theme): self._title_align = "center" # by default, direction of each guide depends on - # the position all the guides + # the position of all the guides position = _property("legend_position") self.direction = _property("legend_direction") if self.direction == "auto": diff --git a/plotnine/guides/guide_colorbar.py b/plotnine/guides/guide_colorbar.py index 9e11a0dee..2b9f5beeb 100644 --- a/plotnine/guides/guide_colorbar.py +++ b/plotnine/guides/guide_colorbar.py @@ -23,23 +23,26 @@ class guide_colorbar(guide): Parameters ---------- - barwidth : float - Width (in pixels) of the colorbar. - barheight : float - Height (in pixels) of the colorbar. The height is multiplied by - a factor of 5. - nbin : int + barwidth : float, default=None + Width (in pixels) of the colorbar. If `None`, the + [](`~plotnine.themes.themeable.legend_key_width`) is + used. The value is multiplied by `1.45`. + barheight : float, default= None + Height (in pixels) of the colorbar. + [](`~plotnine.themes.themeable.legend_key_height`) is + used. The value is multiplied by `5 * 1.45`. + nbin : int, default=20 Number of bins for drawing a colorbar. A larger value yields - a smoother colorbar. Default is 20. - raster : bool + a smoother colorbar + raster : bool, defaut=False Whether to render the colorbar as a raster object. - ticks : bool + ticks : bool, default=True Whether tick marks on colorbar should be visible. - draw_ulim : bool + draw_ulim : bool, default=True Whether to show the upper limit tick marks. - draw_llim : bool + draw_llim : bool, default=TRue Whether to show the lower limit tick marks. - direction : str in ``['horizontal', 'vertical']`` + direction : "horizontal", "vertical", default="horizontal" Direction of the guide. kwargs : dict Parameters passed on to :class:`.guide` diff --git a/plotnine/guides/guide_legend.py b/plotnine/guides/guide_legend.py index 9960b5ff4..d236e53b9 100644 --- a/plotnine/guides/guide_legend.py +++ b/plotnine/guides/guide_legend.py @@ -31,18 +31,18 @@ class guide_legend(guide): Parameters ---------- - nrow : int + nrow : int, default=None Number of rows of legends. - ncol : int + ncol : int, default=None Number of columns of legends. - byrow : bool + byrow : bool, default=False Whether to fill the legend row-wise or column-wise. - keywidth : float + keywidth : float, default=None Width of the legend key. - keyheight : float + keyheight : float, default=None Height of the legend key. kwargs : dict - Parameters passed on to :class:`.guide` + Parameters passed on to [](`~plotnine.guides.guide`). """ # general @@ -62,12 +62,12 @@ def train(self, scale, aesthetic=None): Create the key for the guide The key is a dataframe with two columns: - - scale name : values - - label : labels for each value - scale name is one of the aesthetics - ['x', 'y', 'color', 'fill', 'size', 'shape', 'alpha', - 'stroke'] + - scale name : values + - label : labels for each value + + scale name is one of the aesthetics: `x`, `y`, `color`, + `fill`, `size`, `shape`, `alpha`, `stroke`. Returns this guide if trainning is successful and None if it fails @@ -100,13 +100,17 @@ def merge(self, other): """ Merge overlapped guides - For example:: + For example: - from ggplot import * - gg = ggplot(aes(x='cut', fill='cut', color='cut'), data=diamonds) - gg + stat_bin() + ```python + from ggplot import * + p = ( + ggplot(aes(x='cut', fill='cut', color='cut'), data=diamonds) + + stat_bin() + ) + ``` - This would create similar guides for fill and color where only + Would create similar guides for fill and color where only a single guide would do """ self.key = self.key.merge(other.key) diff --git a/plotnine/guides/guides.py b/plotnine/guides/guides.py index 48284c101..6bd236e98 100644 --- a/plotnine/guides/guides.py +++ b/plotnine/guides/guides.py @@ -40,7 +40,9 @@ class guides(dict): ---------- kwargs : dict aesthetic - guide pairings. e.g - ``color=guide_colorbar()`` + ```python + guides(color=guide_colorbar()) + ``` """ # Determined from the theme when the guides are @@ -226,15 +228,18 @@ def merge(self, gdefs): """ Merge overlapped guides - For example:: + For example: - from plotnine import * - gg = ggplot(mtcars, aes(y='wt', x='mpg', colour='factor(cyl)')) - gg = gg + stat_smooth(aes(fill='factor(cyl)'), method='lm') - gg = gg + geom_point() - gg + ```python + from plotnine import * + p = ( + ggplot(mtcars, aes(y="wt", x="mpg", colour="factor(cyl)")) + + stat_smooth(aes(fill="factor(cyl)"), method="lm") + + geom_point() + ) + ``` - This would create two guides with the same hash + would create two guides with the same hash """ # group guide definitions by hash, and # reduce each group to a single guide diff --git a/plotnine/labels.py b/plotnine/labels.py index 17f1677a6..6342efcbf 100644 --- a/plotnine/labels.py +++ b/plotnine/labels.py @@ -21,7 +21,7 @@ class labs: ---------- kwargs : dict Aesthetics (with scales) to be renamed. You can also - set the ``title`` and ``caption``. + set the `title` and `caption`. """ labels: labels_view diff --git a/plotnine/layer.py b/plotnine/layer.py index 858e92b48..ceeb1ee6f 100644 --- a/plotnine/layer.py +++ b/plotnine/layer.py @@ -34,39 +34,38 @@ class layer: """ Layer - When a ``geom`` or ``stat`` is added to a - [](`~plotnine.ggplot`) object, it creates a single layer. - This class is a representation of that layer. + When a `geom` or `stat` is added to a [](`~plotnine.ggplot`) object, + it creates a single layer. This class is a representation of that layer. Parameters ---------- - geom : geom, optional + geom : geom geom to used to draw this layer. - stat : stat, optional + stat : stat stat used for the statistical transformation of data in this layer - mapping : aes, optional + mapping : aes Aesthetic mappings. - data : dataframe, optional - Data plotted in this layer. If ``None``, the data from + data : dataframe + Data plotted in this layer. If `None`, the data from the [](`~plotnine.ggplot`) object will be used. - position : position, optional + position : position Position object to adjust the geometries in this layer. - inherit_aes : bool, optional - If ``True`` inherit from the aesthetic mappings of - the [](`~plotnine.ggplot`) object. Default ``True``. - show_legend : bool or None, optional + inherit_aes : bool + If `True` inherit from the aesthetic mappings of + the [](`~plotnine.ggplot`) object. + show_legend : bool or None Whether to make up and show a legend for the mappings - of this layer. If ``None`` then an automatic/good choice - is made. Default is ``None``. - raster : bool, optional (default: False) - If ``True``, draw onto this layer a raster (bitmap) object + of this layer. If `None` then an automatic/good choice + is made + raster : bool + If `True`, draw onto this layer a raster (bitmap) object even if the final image format is vector. Notes ----- There is no benefit to manually creating a layer. You should - always use a ``geom`` or ``stat``. + always use a `geom` or `stat`. """ # Data for this layer diff --git a/plotnine/mapping/aes.py b/plotnine/mapping/aes.py index a7fd4fc74..8653e9c58 100644 --- a/plotnine/mapping/aes.py +++ b/plotnine/mapping/aes.py @@ -143,7 +143,7 @@ class aes(Dict[str, Any]): 1. columns in the dataframe 2. variables in the namespace - 3. aesthetic values (columns) calculated by the ``stat`` + 3. aesthetic values (columns) calculated by the `stat` with the column names having precedence over the variables. For expressions, columns in the dataframe that are mapped to diff --git a/plotnine/mapping/evaluation.py b/plotnine/mapping/evaluation.py index 31e9128a2..995a419ff 100644 --- a/plotnine/mapping/evaluation.py +++ b/plotnine/mapping/evaluation.py @@ -124,12 +124,12 @@ def reorder(x, y, fun=np.median, ascending=True): x : list-like Values that will make up the categorical. y : list-like - Values by which ``c`` will be ordered. + Values by which `c` will be ordered. fun : callable - Summarising function to ``x`` for each category in ``c``. + Summarising function to `x` for each category in `c`. Default is the *median*. ascending : bool - If ``True``, the ``c`` is ordered in ascending order of ``x``. + If `True`, the `c` is ordered in ascending order of `x`. Examples -------- diff --git a/plotnine/options.py b/plotnine/options.py index 7902fc2fa..9566e1dfb 100644 --- a/plotnine/options.py +++ b/plotnine/options.py @@ -5,7 +5,7 @@ if typing.TYPE_CHECKING: from typing import Any -#: Development flag, e.g. set to ``True`` to prevent +#: Development flag, e.g. set to `True` to prevent #: the queuing up of figures when errors happen. close_all_figures = False diff --git a/plotnine/positions/position_dodge.py b/plotnine/positions/position_dodge.py index ff0286c1b..129025817 100644 --- a/plotnine/positions/position_dodge.py +++ b/plotnine/positions/position_dodge.py @@ -15,11 +15,11 @@ class position_dodge(position): Parameters ---------- - width: float + width: float, default=None Dodging width, when different to the width of the individual elements. This is useful when you want to align narrow geoms with wider geoms - preserve: str in ``['total', 'single']`` + preserve: "total", "single", default="total" Should dodging preserve the total width of all elements at a position, or the width of a single element? """ diff --git a/plotnine/positions/position_dodge2.py b/plotnine/positions/position_dodge2.py index 441405004..4505a769b 100644 --- a/plotnine/positions/position_dodge2.py +++ b/plotnine/positions/position_dodge2.py @@ -24,21 +24,20 @@ class position_dodge2(position_dodge): Parameters ---------- - width: float + width: float, default=None Dodging width, when different to the width of the individual elements. This is useful when you want to align narrow geoms with wider geoms - preserve: str in ``['total', 'single']`` + preserve: "total", "single", default="total" Should dodging preserve the total width of all elements at a position, or the width of a single element? - padding : float + padding : float, default=0.1 Padding between elements at the same position. Elements are shrunk by this proportion to allow space - between them (Default: 0.1) - reverse : bool + between them. + reverse : bool, default=False Reverse the default ordering of the groups. This is useful if you're rotating both the plot and legend. - (Default: False) """ REQUIRED_AES = {"x"} diff --git a/plotnine/positions/position_jitter.py b/plotnine/positions/position_jitter.py index f2f505c17..163e3c45a 100644 --- a/plotnine/positions/position_jitter.py +++ b/plotnine/positions/position_jitter.py @@ -18,14 +18,14 @@ class position_jitter(position): Parameters ---------- - width : float + width : float, default=None Proportion to jitter in horizontal direction. - Default is ``0.4`` of the resolution of the data. - height : float + If `None`, `0.4` of the resolution of the data. + height : float, default=None Proportion to jitter in vertical direction. - Default is ``0.4`` of the resolution of the data. - random_state : int or ~numpy.random.RandomState, optional - Seed or Random number generator to use. If ``None``, then + If `None`, `0.4` of the resolution of the data. + random_state : int, ~numpy.random.RandomState, default=None + Seed or Random number generator to use. If `None`, then numpy global generator :class:`numpy.random` is used. """ diff --git a/plotnine/positions/position_jitterdodge.py b/plotnine/positions/position_jitterdodge.py index a893a8957..6153b5e2c 100644 --- a/plotnine/positions/position_jitterdodge.py +++ b/plotnine/positions/position_jitterdodge.py @@ -19,17 +19,15 @@ class position_jitterdodge(position): Parameters ---------- - jitter_width : float + jitter_width : float, default=None Proportion to jitter in horizontal direction. - Default is ``0.4`` of the resolution of the data. - jitter_height : float + If `None`, `0.4` of the resolution of the data. + jitter_height : float, default=0 Proportion to jitter in vertical direction. - Default is ``0.0`` of the resolution of the data. - dodge_width : float + dodge_width : float, default=0.75 Amount to dodge in horizontal direction. - Default is ``0.75`` - random_state : int or ~numpy.random.RandomState, optional - Seed or Random number generator to use. If ``None``, then + random_state : int, ~numpy.random.RandomState, default=None + Seed or Random number generator to use. If `None`, then numpy global generator :class:`numpy.random` is used. """ diff --git a/plotnine/positions/position_nudge.py b/plotnine/positions/position_nudge.py index 6debe77fc..c597bc83f 100644 --- a/plotnine/positions/position_nudge.py +++ b/plotnine/positions/position_nudge.py @@ -17,9 +17,9 @@ class position_nudge(position): Parameters ---------- - x : float + x : float, default=0 Horizontal nudge - y : float + y : float, default=0 Vertical nudge """ diff --git a/plotnine/positions/position_stack.py b/plotnine/positions/position_stack.py index 3ebeb85de..47c4c1869 100644 --- a/plotnine/positions/position_stack.py +++ b/plotnine/positions/position_stack.py @@ -16,6 +16,12 @@ class position_stack(position): The objects to stack are those that have an overlapping x range. + + Parameters + ---------- + vjust: float + By what fraction to avoid overlapping the lower object, + where `0` gives a complete overlap and `1` gives no overlap. """ fill = False diff --git a/plotnine/qplot.py b/plotnine/qplot.py index e457c257c..3dc54794b 100644 --- a/plotnine/qplot.py +++ b/plotnine/qplot.py @@ -56,9 +56,9 @@ def qplot( will create one, extracting arrays from the current environment. geom : str | list - *geom(s)* to do the drawing. If ``auto``, defaults - to 'point' if ``x`` and ``y`` are specified or - 'histogram' if only ``x`` is specified. + *geom(s)* to do the drawing. If `auto`, defaults + to 'point' if `x` and `y` are specified or + 'histogram' if only `x` is specified. facets : str Facets margins : bool | list[str] diff --git a/plotnine/scales/limits.py b/plotnine/scales/limits.py index d130fabc5..12b51ff9c 100644 --- a/plotnine/scales/limits.py +++ b/plotnine/scales/limits.py @@ -93,7 +93,7 @@ class xlim(_lim): limits : array_like Min and max limits. Must be of size 2. You can also pass two values e.g - ``xlim(40, 100)`` + `xlim(40, 100)` """ aesthetic = "x" @@ -108,11 +108,11 @@ class ylim(_lim): limits : array_like Min and max limits. Must be of size 2. You can also pass two values e.g - ``ylim(40, 100)`` + `ylim(40, 100)` Notes ----- - If the 2nd value of ``limits`` is less than + If the 2nd value of `limits` is less than the first, a reversed scale will be created. """ @@ -183,11 +183,11 @@ class lims: ---------- kwargs : dict Aesthetic and the values of the limits. - e.g ``x=(40, 100)`` + e.g `x=(40, 100)` Notes ----- - If the 2nd value of ``limits`` is less than + If the 2nd value of `limits` is less than the first, a reversed scale will be created. """ diff --git a/plotnine/scales/scale.py b/plotnine/scales/scale.py index ecce8e6bd..6998f0492 100644 --- a/plotnine/scales/scale.py +++ b/plotnine/scales/scale.py @@ -39,53 +39,55 @@ class scale(metaclass=Registry): Parameters ---------- - breaks : array_like or callable, optional - Major break points. Alternatively, a callable that + breaks : bool, list, callable, default=True + List of major break points. Or a callable that takes a tuple of limits and returns a list of breaks. - Default is to automatically calculate the breaks. - expand : tuple, optional + If `True`, automatically calculate the breaks. + expand : tuple, default=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:: + values are in this order: - (mul, add) - (mul_low, add_low, mul_high, add_high) + ``` + (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. + - `(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. - name : str, optional + name : str, default=None Name used as the label of the scale. This is what shows up as the axis label or legend title. Suitable defaults are chosen depending on the type of scale. - labels : list or callable, optional - List of :class:`str`. Labels at the `breaks`. + labels : bool, list, callable, default=True + List of :py:class:`str`. Labels at the `breaks`. Alternatively, a callable that takes an array_like of break points as input and returns a list of strings. - limits : array_like, optional + limits : array_like, default=None Limits of the scale. Most commonly, these are the min & max values for the scales. For scales that deal with categoricals, these may be a subset or superset of the categories. - na_value : scalar + na_value : scalar, default=float("nan") What value to assign to missing values. Default - is to assign ``np.nan``. - palette : callable, optional + is to assign `np.nan`. + palette : callable, default=None Function to map data points onto the scale. Most scales define their own palettes. - aesthetics : list, optional - list of :class:`str`. Aesthetics covered by the + aesthetics : list, str, default=None + list of :py:class:`str`. Aesthetics covered by the scale. These are defined by each scale and the user should probably not change them. Have fun. """ diff --git a/plotnine/scales/scale_alpha.py b/plotnine/scales/scale_alpha.py index e1c942aa4..b9dac48e2 100644 --- a/plotnine/scales/scale_alpha.py +++ b/plotnine/scales/scale_alpha.py @@ -17,9 +17,9 @@ class scale_alpha(scale_continuous): Parameters ---------- - range : array_like + range : tuple Range ([Minimum, Maximum]) of output alpha values. - Should be between 0 and 1. Default is ``(0.1, 1)`` + Should be between 0 and 1. {superclass_parameters} """ @@ -43,9 +43,9 @@ class scale_alpha_ordinal(scale_discrete): Parameters ---------- - range : array_like + range : tuple Range ([Minimum, Maximum]) of output alpha values. - Should be between 0 and 1. Default is ``(0.1, 1)`` + Should be between 0 and 1. {superclass_parameters} """ @@ -86,9 +86,9 @@ class scale_alpha_datetime(scale_datetime): Parameters ---------- - range : array_like + range : tuple Range ([Minimum, Maximum]) of output alpha values. - Should be between 0 and 1. Default is ``(0.1, 1)`` + Should be between 0 and 1. {superclass_parameters} """ diff --git a/plotnine/scales/scale_color.py b/plotnine/scales/scale_color.py index 858800e7c..9a0340f88 100644 --- a/plotnine/scales/scale_color.py +++ b/plotnine/scales/scale_color.py @@ -27,20 +27,18 @@ class scale_color_hue(scale_discrete): ---------- h : float first hue. Must be in the range [0, 1] - Default is ``0.01`` l : float lightness. Must be in the range [0, 1] - Default is ``0.6`` s : float saturation. Must be in the range [0, 1] - Default is ``0.65`` - colorspace : str in ``['hls', 'husl']`` - Color space to use. - `hls `_ - `husl `_ + colorspace : str, default="hls" + Color space to use. Should be one of + [hls](https://en.wikipedia.org/wiki/HSL_and_HSV) + or + [husl](http://www.husl-colors.org/). {superclass_parameters} - na_value : str - Color of missing values. Default is ``'#7F7F7F'`` + na_value : str, default="#7F7F7F" + Color of missing values. """ _aesthetics = ["color"] @@ -82,20 +80,19 @@ class scale_color_brewer(scale_discrete): Parameters ---------- - type : str in ``['seq', 'div', 'qual']`` + type : "seq", "div", "qual", default="seq" Type of data. Sequential, diverging or qualitative - palette : int | str + palette : int, str, default=1 If a string, will use that named palette. If a number, will index into the list of palettes - of appropriate type. Default is 1 - direction: int in ``[-1, 1]`` - Sets the order of colors in the scale. If 1, - the default, colors are as output by - mizani.palettes.brewer_pal(). If -1, + of appropriate type. + direction: 1 or -1, default=1 + Sets the order of colors in the scale. If 1, colors are + as output by [](`~mizani.palettes.brewer_pal`). If -1, the order of colors is reversed. {superclass_parameters} - na_value : str - Color of missing values. Default is ``'None'`` + na_value : str, default="#7F7F7F" + Color of missing values. """ _aesthetics = ["color"] @@ -134,12 +131,10 @@ class scale_color_grey(scale_discrete): Parameters ---------- - start : float + start : float, default=0.2 grey value at low end of palette. - Default is 0.2 - end : float + end : float, default=0.8 grey value at high end of palette - Default is 0.8 {superclass_parameters} """ @@ -180,8 +175,8 @@ class scale_color_gradient(scale_continuous): high : str high color {superclass_parameters} - na_value : str - Color of missing values. Default is ``'None'`` + na_value : str, default="#7F7F7F" + Color of missing values. See Also -------- @@ -224,17 +219,17 @@ class scale_color_desaturate(scale_continuous): Parameters ---------- - color : str, optional (Default: 'red') + color : str, default="red" Color to desaturate - prop : float, optional (Default: 0) + prop : float, default=0 Saturation channel of color will be multiplied by this value. - reverse : bool, optional (Default: False) + reverse : bool, default=False Whether to go from color to desaturated color or desaturated color to color. {superclass_parameters} - na_value : str - Color of missing values. Default is ``'None'`` + na_value : str, default="#7F7F7F" + Color of missing values. """ _aesthetics = ["color"] @@ -269,17 +264,17 @@ class scale_color_gradient2(scale_continuous): Parameters ---------- - low : str, optional + low : str low color - mid : str, optional + mid : str mid point color - high : str, optional + high : str high color - midpoint : float, optional (Default: 0) + midpoint : float, default=0 Mid point of the input data range. {superclass_parameters} - na_value : str - Color of missing values. Default is ``'None'`` + na_value : str, default="#7F7F7F" + Color of missing values See Also -------- @@ -332,15 +327,15 @@ class scale_color_gradientn(scale_continuous): Parameters ---------- - colors : list + colors : list, list of colors - values : list, optional + values : list, default=None 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 {superclass_parameters} - na_value : str - Color of missing values. Default is ``'None'`` + na_value : str, default="#7F7F7F" + Color of missing values See Also -------- @@ -380,29 +375,29 @@ class scale_color_distiller(scale_color_gradientn): This is a convinience scale around [](`~plotnine.scales.scale_color_gradientn`) with colors from - `colorbrewer.org `_. It smoothly + [colorbrewer.org](http://colorbrewer2.org). It smoothly interpolates 7 colors from a brewer palette to create a continuous palette. Parameters ---------- - type : str in ``['seq', 'div']`` + type : "seq", "div", default="seq" Type of data. Sequential, diverging or qualitative - palette : int | str + palette : int, str, default=1 If a string, will use that named palette. If a number, will index into the list of palettes of appropriate type. Default is 1 - values : list, optional + values : list, default=None 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 - direction: int in ``[-1, 1]`` + direction: -1, 1, default=-1 Sets the order of colors in the scale. If 1 - colors are as output by mizani.palettes.brewer_pal(). - If -1, the default, the order of colors is reversed. + colors are as output by [](`~mizani.palettes.brewer_pal`). + If -1, the order of colors is reversed. {superclass_parameters} - na_value : str - Color of missing values. Default is ``'None'`` + na_value : str, default="#7F7F7F" + Color of missing values. """ _aesthetics = ["color"] @@ -457,18 +452,14 @@ class scale_color_cmap(scale_continuous): Parameters ---------- - cmap_name : str + cmap_name : str, default="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 the + of `matplotlib.cm.cmap_d.keys()` or see the `documentation `_. - lut : None | int - This is the number of entries desired in the - lookup table. Default is `None`, leave it up - Matplotlib. {superclass_parameters} - na_value : str - Color of missing values. Default is ``'None'`` + na_value : str, default="#7F7F7F" + Color of missing values. See Also -------- @@ -508,19 +499,15 @@ class scale_color_cmap_d(scale_discrete): Parameters ---------- - cmap_name : str + cmap_name : str, default="viridis" A standard Matplotlib colormap name. It must be of type :class:`matplotlib.colors.ListedColormap`. . The default is `viridis`. For the list of names checkout - the output of ``matplotlib.cm.cmap_d.keys()`` or see the + the output of `matplotlib.cm.cmap_d.keys()` or see the `documentation `_. - lut : None | int - This is the number of entries desired in the - lookup table. Default is `None`, leave it up - Matplotlib. {superclass_parameters} - na_value : str - Color of missing values. Default is ``'None'`` + na_value : str, default="#7F7F7F" + Color of missing values. See Also -------- diff --git a/plotnine/scales/scale_continuous.py b/plotnine/scales/scale_continuous.py index 710a0ab83..f55064357 100644 --- a/plotnine/scales/scale_continuous.py +++ b/plotnine/scales/scale_continuous.py @@ -47,20 +47,20 @@ class scale_continuous(scale): trans : str | function Name of a trans function or a trans function. See :mod:`mizani.transforms` for possible options. - oob : function + oob : callable, default=mizani.bounds.censor Function to deal with out of bounds (limits) data points. Default is to turn them into - ``np.nan``, which then get dropped. - minor_breaks : list-like or int or callable or None + `np.nan`, which then get dropped. + minor_breaks : list, int, callable, default=None 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 + `func(limits)` and return a list-like of consisting of the minor break points. - If ``None``, no minor breaks are calculated. + If `None`, no minor breaks are calculated. The default is to automatically calculate them. - rescaler : function, optional + rescaler : callable, default=mizani.bounds.rescale 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 diff --git a/plotnine/scales/scale_datetime.py b/plotnine/scales/scale_datetime.py index e3d5203cf..52ec0d31e 100644 --- a/plotnine/scales/scale_datetime.py +++ b/plotnine/scales/scale_datetime.py @@ -13,21 +13,21 @@ class scale_datetime(scale_continuous): Parameters ---------- - date_breaks : str + date_breaks : str, default=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 + `date_breaks` takes precedence over + `breaks`. + date_labels : str, default=None Format string for the labels. See :ref:`strftime `. - If specified, ``date_labels`` takes precedence over - ``labels``. - date_minor_breaks : str + If specified, `date_labels` takes precedence over + `labels`. + date_minor_breaks : str, default=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``. + `date_minor_breaks` takes precedence over + `minor_breaks`. {superclass_parameters} """ diff --git a/plotnine/scales/scale_discrete.py b/plotnine/scales/scale_discrete.py index 07be7d364..165934e12 100644 --- a/plotnine/scales/scale_discrete.py +++ b/plotnine/scales/scale_discrete.py @@ -37,23 +37,23 @@ class scale_discrete(scale): Parameters ---------- {superclass_parameters} - limits : array_like, optional + limits : array_like, default=None Limits of the scale. For scales that deal with categoricals, these may be a subset or superset of the categories. Data values that are not in the limits will be treated as missing data and represented with - the ``na_value``. - drop : bool + the `na_value`. + drop : bool, default=True Whether to drop unused categories from the scale - na_translate : bool - If ``True`` translate missing values and show them. - If ``False`` remove missing values. Default value is - ``True`` + na_translate : bool, default=True + If `True` translate missing values and show them. + If `False` remove missing values. Default value is + `True` na_value : object - If ``na_translate=True``, what aesthetic value should be + 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 + apply to position scales where `nan` is always placed on the right. """ diff --git a/plotnine/scales/scale_identity.py b/plotnine/scales/scale_identity.py index 4e4c332a6..7019fcc71 100644 --- a/plotnine/scales/scale_identity.py +++ b/plotnine/scales/scale_identity.py @@ -46,8 +46,8 @@ class scale_color_identity(MapTrainMixin, scale_discrete): Parameters ---------- {superclass_parameters} - guide : None | 'legend' - Whether to include a legend. Default is None. + guide : None, 'legend', default=None + Whether to include a legend. """ _aesthetics = ["color"] @@ -74,8 +74,8 @@ class scale_shape_identity(MapTrainMixin, scale_discrete): Parameters ---------- {superclass_parameters} - guide : None | 'legend' - Whether to include a legend. Default is None. + guide : None, 'legend', default=None + Whether to include a legend. """ _aesthetics = ["shape"] @@ -89,8 +89,8 @@ class scale_linetype_identity(MapTrainMixin, scale_discrete): Parameters ---------- {superclass_parameters} - guide : None | 'legend' - Whether to include a legend. Default is None. + guide : None, 'legend', default=None + Whether to include a legend. """ _aesthetics = ["linetype"] @@ -104,8 +104,8 @@ class scale_alpha_identity(MapTrainMixin, scale_continuous): Parameters ---------- {superclass_parameters} - guide : None | 'legend' - Whether to include a legend. Default is None. + guide : None, 'legend', default=None + Whether to include a legend. """ _aesthetics = ["alpha"] @@ -119,8 +119,8 @@ class scale_size_identity(MapTrainMixin, scale_continuous): Parameters ---------- {superclass_parameters} - guide : None | 'legend' - Whether to include a legend. Default is None. + guide : None, 'legend', default=None + Whether to include a legend. """ _aesthetics = ["size"] diff --git a/plotnine/scales/scale_linetype.py b/plotnine/scales/scale_linetype.py index 8b9663c02..ca07de14f 100644 --- a/plotnine/scales/scale_linetype.py +++ b/plotnine/scales/scale_linetype.py @@ -21,7 +21,7 @@ class scale_linetype(scale_discrete): Notes ----- The available linetypes are - ``'solid', 'dashed', 'dashdot', 'dotted'`` + `'solid', 'dashed', 'dashdot', 'dotted'` If you need more custom linetypes, use [](`~plotnine.scales.scale_linetype_manual`) """ diff --git a/plotnine/scales/scale_manual.py b/plotnine/scales/scale_manual.py index 5104c81c4..64738c871 100644 --- a/plotnine/scales/scale_manual.py +++ b/plotnine/scales/scale_manual.py @@ -55,7 +55,7 @@ class scale_color_manual(_scale_manual): ---------- values : array_like | dict Colors that make up the palette. The values will be matched with - the ``limits`` of the scale or the ``breaks`` if provided. + the `limits` of the scale or the `breaks` if provided. If it is a dict then it should map data values to colors. {superclass_parameters} @@ -74,7 +74,7 @@ class scale_fill_manual(_scale_manual): ---------- values : array_like | dict Colors that make up the palette. The values will be matched with - the ``limits`` of the scale or the ``breaks`` if provided. + the `limits` of the scale or the `breaks` if provided. If it is a dict then it should map data values to colors. {superclass_parameters} """ @@ -93,8 +93,8 @@ class scale_shape_manual(_scale_manual): values : array_like | dict Shapes that make up the palette. See :mod:`matplotlib.markers.` for list of all possible - shapes. The values will be matched with the ``limits`` - of the scale or the ``breaks`` if provided. + 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. {superclass_parameters} @@ -113,25 +113,25 @@ class scale_linetype_manual(_scale_manual): Parameters ---------- - values : list-like | dict + values : list | dict Linetypes that make up the palette. Possible values of the list are: - 1. Strings like + 1. Strings like - :: + ```python + 'solid' # solid line + 'dashed' # dashed line + 'dashdot' # dash-dotted line + 'dotted' # dotted line + 'None' or ' ' or '' # draw nothing + ``` - 'solid' # solid line - 'dashed' # dashed line - 'dashdot' # dash-dotted line - 'dotted' # dotted line - 'None' or ' ' or '' # draw nothing + 2. Tuples of the form (offset, (on, off, on, off, ....)) + e.g. (0, (1, 1)), (1, (2, 2)), (2, (5, 3, 1, 3)) - 2. Tuples of the form (offset, (on, off, on, off, ....)) - e.g. (0, (1, 1)), (1, (2, 2)), (2, (5, 3, 1, 3)) - - The values will be matched with the ``limits`` of the scale - or the ``breaks`` if provided. + 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 linetypes. {superclass_parameters} @@ -161,7 +161,7 @@ class scale_alpha_manual(_scale_manual): values : array_like | dict Alpha values (in the [0, 1] range) that make up the palette. The values will be matched with the - ``limits`` of the scale or the ``breaks`` if provided. + `limits` of the scale or the `breaks` if provided. If it is a dict then it should map data values to alpha values. {superclass_parameters} @@ -179,7 +179,7 @@ class scale_size_manual(_scale_manual): ---------- values : array_like | dict Sizes that make up the palette. The values will be matched - with the ``limits`` of the scale or the ``breaks`` if provided. + with the `limits` of the scale or the `breaks` if provided. If it is a dict then it should map data values to sizes. {superclass_parameters} """ diff --git a/plotnine/scales/scale_shape.py b/plotnine/scales/scale_shape.py index 779e886fa..d04835c89 100644 --- a/plotnine/scales/scale_shape.py +++ b/plotnine/scales/scale_shape.py @@ -57,7 +57,7 @@ class scale_shape(scale_discrete): Parameters ---------- unfilled : bool - If ``True``, then all shapes will have no interiors + If `True`, then all shapes will have no interiors that can be a filled. {superclass_parameters} """ diff --git a/plotnine/scales/scale_stroke.py b/plotnine/scales/scale_stroke.py index 7c00dbb00..a1289de37 100644 --- a/plotnine/scales/scale_stroke.py +++ b/plotnine/scales/scale_stroke.py @@ -16,9 +16,9 @@ class scale_stroke_continuous(scale_continuous): Parameters ---------- - range : array_like + range : tuple Range ([Minimum, Maximum]) of output stroke values. - Should be between 0 and 1. Default is ``(1, 6)`` + Should be between 0 and 1. {superclass_parameters} """ @@ -39,9 +39,9 @@ class scale_stroke_ordinal(scale_discrete): Parameters ---------- - range : array_like + range : tuple Range ([Minimum, Maximum]) of output stroke values. - Should be between 0 and 1. Default is ``(1, 6)`` + Should be between 0 and 1. {superclass_parameters} """ diff --git a/plotnine/scales/scale_xy.py b/plotnine/scales/scale_xy.py index 0a710b70c..99018f0db 100644 --- a/plotnine/scales/scale_xy.py +++ b/plotnine/scales/scale_xy.py @@ -41,7 +41,7 @@ class scale_position_discrete(scale_discrete): Parameters ---------- {superclass_parameters} - limits : array_like, optional + limits : array_like, default=None Limits of the scale. For discrete scale, these are the categories (unique values) of the variable. For scales that deal with categoricals, these may diff --git a/plotnine/stats/stat_bin.py b/plotnine/stats/stat_bin.py index 0f0c20362..bfc8acf4f 100644 --- a/plotnine/stats/stat_bin.py +++ b/plotnine/stats/stat_bin.py @@ -30,43 +30,43 @@ class stat_bin(stat): value, exploring multiple widths to find the best to illustrate the stories in your data. bins : int, optional (default: None) - Number of bins. Overridden by binwidth. If :py:`None`, + Number of bins. Overridden by binwidth. If `None`{.py}, a number is computed using the freedman-diaconis method. breaks : array-like, optional (default: None) - Bin boundaries. This supercedes the ``binwidth``, ``bins``, - ``center`` and ``boundary``. + Bin boundaries. This supercedes the `binwidth`, `bins`, + `center` and `boundary`. center : float, optional (default: None) The center of one of the bins. Note that if center is above or below the range of the data, things will be shifted by an appropriate number of widths. To center on integers, for - example, use :py:`width=1` and :py:`center=0`, even if 0 i + example, use `width=1`{.py} and :py:`center=0`, even if 0 i s outside the range of the data. At most one of center and boundary may be specified. boundary : float, optional (default: None) A boundary between two bins. As with center, things are shifted when boundary is outside the range of the data. - For example, to center on integers, use :py:`width=1` and - :py:`boundary=0.5`, even if 1 is outside the range of the + For example, to center on integers, use `width=1`{.py} and + `boundary=0.5`{.py}, even if 1 is outside the range of the data. At most one of center and boundary may be specified. closed : str, optional (default: right) Which edge of the bins is included, *left* or *right*. pad : bool, optional (default: False) - If :py:`True`, adds empty bins at either side of x. + If `True`{.py}, adds empty bins at either side of x. This ensures that frequency polygons touch 0. """ _aesthetics_doc = """ {aesthetics_table} - .. rubric:: Options for computed aesthetics + **Options for computed aesthetics** - :: - - 'count' # number of points in bin - 'density' # density of points in bin, scaled to integrate to 1 - 'ncount' # count, scaled to maximum of 1 - 'ndensity' # density, scaled to maximum of 1 - 'ngroup' # number of points in group + ```python + "count" # number of points in bin + "density" # density of points in bin, scaled to integrate to 1 + "ncount" # count, scaled to maximum of 1 + "ndensity" # density, scaled to maximum of 1 + "ngroup" # number of points in group + ``` """ REQUIRED_AES = {"x"} diff --git a/plotnine/stats/stat_bin_2d.py b/plotnine/stats/stat_bin_2d.py index db2a1879c..7174f7157 100644 --- a/plotnine/stats/stat_bin_2d.py +++ b/plotnine/stats/stat_bin_2d.py @@ -24,32 +24,32 @@ class stat_bin_2d(stat): bins : int, optional (default: 30) Number of bins. Overridden by binwidth. breaks : array-like(s), optional (default: None) - Bin boundaries. This supercedes the ``binwidth``, ``bins``, - ``center`` and ``boundary``. It can be an array_like or + Bin boundaries. This supercedes the `binwidth`, `bins`, + `center` and `boundary`. It can be an array_like or a list of two array_likes to provide distinct breaks for - the ``x`` and ``y`` axes. + the `x` and `y` axes. binwidth : float, optional (default: None) The width of the bins. The default is to use bins bins that cover the range of the data. You should always override this value, exploring multiple widths to find the best to illustrate the stories in your data. drop : bool, optional (default: False) - If :py:`True`, removes all cells with zero counts. + If `True`{.py}, removes all cells with zero counts. """ _aesthetics_doc = """ {aesthetics_table} - .. rubric:: Options for computed aesthetics + **Options for computed aesthetics** - :: - - 'xmin' # x lower bound for the bin - 'xmax' # x upper bound for the bin - 'ymin' # y lower bound for the bin - 'ymax' # y upper bound for the bin - 'count' # number of points in bin - 'density' # density of points in bin, scaled to integrate to 1 + ```python + "xmin" # x lower bound for the bin + "xmax" # x upper bound for the bin + "ymin" # y lower bound for the bin + "ymax" # y upper bound for the bin + "count" # number of points in bin + "density" # density of points in bin, scaled to integrate to 1 + ``` """ REQUIRED_AES = {"x", "y"} diff --git a/plotnine/stats/stat_bindot.py b/plotnine/stats/stat_bindot.py index ef04efd71..2c572eb63 100644 --- a/plotnine/stats/stat_bindot.py +++ b/plotnine/stats/stat_bindot.py @@ -28,41 +28,37 @@ class stat_bindot(stat): Parameters ---------- {common_parameters} - bins : int, optional (default: None) - Number of bins. Overridden by binwidth. If :py:`None`, + bins : int, default=None + Number of bins. Overridden by binwidth. If `None`{.py}, a number is computed using the freedman-diaconis method. - binwidth : float, optional (default: None) - When :py:`method='dotdensity'`, this specifies the maximum - binwidth. When :py:`method='histodot'`, this specifies the - binwidth. This supercedes the ``bins``. - origin : float, optional (default: None) - When :py:`method='histodot'`, origin of the first bin. + binwidth : float, default=None + When `method='dotdensity'`{.py}, this specifies the maximum + binwidth. When `method='histodot'`{.py}, this specifies the + binwidth. This supercedes the `bins`. + origin : float, default=None + When `method='histodot'`{.py}, origin of the first bin. width : float, optional (default: 0.9) - When :py:`binaxis='y'`, the spacing of the dotstacks for + When `binaxis='y'`{.py}, the spacing of the dotstacks for dodging. - binaxis : str, optional (default: x) - Axis to bin along. Either :py:`'x'` or :py:`'y'` - method : str, optional (default: dotdensity) - One of *dotdensity* or *histodot*. These provide either of - dot-density binning or fixed bin widths. - binpositions : str, optional (default: bygroup) - Position of the bins when :py:`method='dotdensity'`. The value - is one of:: - - 'bygroup' # positions of the bins for each group are - # determined separately. - 'all' # positions of the bins are determined with all - # data taken together. This aligns the dots - # stacks across multiple groups. - - drop : bool, optional (default: False) - If :py:`True`, remove all bins with zero counts. - right : bool, optional (default: True) - When :py:`method='histodot'`, :py:`True` means include right - edge of the bins and if :py:`False` the left edge is included. - breaks : array-like, optional (default: None) - Bin boundaries for :py:`method='histodot'`. This supercedes the - ``binwidth`` and ``bins``. + binaxis : "x", "y", default="x" + Axis to bin along. + method : "dotdensity", "histodot", default="dotdensity" + Whether to do dot-density binning or fixed widths binning. + binpositions : "all", "bygroup", default="bygroup" + Position of the bins when `method="dotdensity"`{.py}. The value + - `bygroup` - positions of the bins for each group are + determined separately. + - `all` - positions of the bins are determined with all + data taken together. This aligns the dots + stacks across multiple groups. + drop : bool, default=False + If `True`{.py}, remove all bins with zero counts. + right : bool, default=True + When `method='histodot'`{.py}, :py:`True` means include right + edge of the bins and if `False`{.py} the left edge is included. + breaks : array-like, default=None + Bin boundaries for `method='histodot'`{.py}. This supercedes the + `binwidth` and `bins`. See Also -------- @@ -72,14 +68,14 @@ class stat_bindot(stat): _aesthetics_doc = """ {aesthetics_table} - .. rubric:: Options for computed aesthetics + **Options for computed aesthetics** - :: - - 'count' # number of points in bin - 'density' # density of points in bin, scaled to integrate to 1 - 'ncount' # count, scaled to maximum of 1 - 'ndensity' # density, scaled to maximum of 1 + ```python + "count" # number of points in bin + "density" # density of points in bin, scaled to integrate to 1 + "ncount" # count, scaled to maximum of 1 + "ndensity" # density, scaled to maximum of 1 + ``` """ diff --git a/plotnine/stats/stat_boxplot.py b/plotnine/stats/stat_boxplot.py index ea29e765e..b885705b5 100644 --- a/plotnine/stats/stat_boxplot.py +++ b/plotnine/stats/stat_boxplot.py @@ -17,7 +17,7 @@ class stat_boxplot(stat): Parameters ---------- {common_parameters} - coef : float, optional (default: 1.5) + coef : float, default=1.5 Length of the whiskers as a multiple of the Interquartile Range. @@ -29,29 +29,33 @@ class stat_boxplot(stat): _aesthetics_doc = """ {aesthetics_table} - .. rubric:: Options for computed aesthetics + **Options for computed aesthetics** - :: + ```python + "width" # width of boxplot + "lower" # lower hinge, 25% quantile + "middle" # median, 50% quantile + "upper" # upper hinge, 75% quantile - 'width' # width of boxplot - 'lower' # lower hinge, 25% quantile - 'middle' # median, 50% quantile - 'upper' # upper hinge, 75% quantile + # lower edge of notch, computed as; + # median - 1.58 * IQR / sqrt(n) + "notchlower" - 'notchlower' # lower edge of notch, computed as; - # median - 1.58 * IQR / sqrt(n) + # upper edge of notch, computed as; + # median + 1.58 * IQR / sqrt(n) + "notchupper" - 'notchupper' # upper edge of notch, computed as; - # median + 1.58 * IQR / sqrt(n) + # lower whisker, computed as; smallest observation + # greater than or equal to lower hinge - 1.5 * IQR + "ymin" - 'ymin' # lower whisker, computed as; smallest observation - # greater than or equal to lower hinge - 1.5 * IQR - - 'ymax' # upper whisker, computed as; largest observation - # less than or equal to upper hinge + 1.5 * IQR + # upper whisker, computed as; largest observation + # less than or equal to upper hinge + 1.5 * IQR + "ymax" + ``` Calculated aesthetics are accessed using the `after_stat` function. - e.g. :py:`after_stat('width')`. + e.g. `after_stat('width')`{.py}. """ REQUIRED_AES = {"x", "y"} @@ -167,10 +171,10 @@ def weighted_boxplot_stats(x, weights=None, whis=1.5): The data beyond the whisker are considered outliers. If a float, the lower whisker is at the lowest datum above - ``Q1 - whis*(Q3-Q1)``, and the upper whisker at the highest - datum below ``Q3 + whis*(Q3-Q1)``, where Q1 and Q3 are the + `Q1 - whis*(Q3-Q1)`, and the upper whisker at the highest + datum below `Q3 + whis*(Q3-Q1)`, where Q1 and Q3 are the first and third quartiles. The default value of - ``whis = 1.5`` corresponds to Tukey's original definition of + `whis = 1.5` corresponds to Tukey's original definition of boxplots. Notes diff --git a/plotnine/stats/stat_count.py b/plotnine/stats/stat_count.py index ecfc74556..04eb6ba45 100644 --- a/plotnine/stats/stat_count.py +++ b/plotnine/stats/stat_count.py @@ -18,9 +18,8 @@ class stat_count(stat): Parameters ---------- {common_parameters} - width : float, optional (default: None) - Bar width. By default, set to 90% of the - resolution of the data + width : float, default=None + Bar width. If None, set to 90% of the resolution of the data. See Also -------- @@ -30,12 +29,12 @@ class stat_count(stat): _aesthetics_doc = """ {aesthetics_table} - .. rubric:: Options for computed aesthetics + **Options for computed aesthetics** - :: - - 'count' # Number of observations at a position - 'prop' # Ratio of points in the panel at a position + ```python + "count" # Number of observations at a position + "prop" # Ratio of points in the panel at a position + ``` """ diff --git a/plotnine/stats/stat_density.py b/plotnine/stats/stat_density.py index 4b9ec6738..e9aa92b7c 100644 --- a/plotnine/stats/stat_density.py +++ b/plotnine/stats/stat_density.py @@ -28,53 +28,55 @@ class stat_density(stat): Parameters ---------- {common_parameters} - kernel : str, optional (default: 'gaussian') - Kernel used for density estimation. One of:: - - 'biweight' - 'cosine' - 'cosine2' - 'epanechnikov' - 'gaussian' - 'triangular' - 'triweight' - 'uniform' - - adjust : float, optional (default: 1) - An adjustment factor for the ``bw``. Bandwidth becomes - :py:`bw * adjust`. + kernel : str, default="gaussian" + Kernel used for density estimation. One of: + ```python + "biweight" + "cosine" + "cosine2" + "epanechnikov" + "gaussian" + "triangular" + "triweight" + "uniform" + ``` + adjust : float, default=1 + An adjustment factor for the `bw`. Bandwidth becomes + `bw * adjust`{.py}. Adjustment of the bandwidth. - trim : bool, optional (default: False) + trim : bool, default=False This parameter only matters if you are displaying multiple - densities in one plot. If :py:`False`, the default, each + densities in one plot. If `False`{.py}, the default, each density is computed on the full range of the data. If - :py:`True`, each density is computed over the range of that + `True`{.py}, each density is computed over the range of that group; this typically means the estimated x values will not line-up, and hence you won't be able to stack density values. - n : int, optional(default: 1024) + n : int, default=1024 Number of equally spaced points at which the density is to be estimated. For efficient computation, it should be a power of two. - gridsize : int, optional (default: None) - If gridsize is :py:`None`, :py:`max(len(x), 50)` is used. - bw : str or float, optional (default: 'nrd0') + gridsize : int, default=None + If gridsize is `None`{.py}, `max(len(x), 50)`{.py} is used. + bw : str, float, default="nrd0" The bandwidth to use, If a float is given, it is the bandwidth. - The :py:`str` choices are:: - - 'nrd0' - 'normal_reference' - 'scott' - 'silverman' - - ``nrd0`` is a port of ``stats::bw.nrd0`` in R; it is eqiuvalent - to ``silverman`` when there is more than 1 value in a group. - cut : float, optional (default: 3) + The options are: + + ```python + "nrd0" + "normal_reference" + "scott" + "silverman" + ``` + + `nrd0` is a port of `stats::bw.nrd0` in R; it is eqiuvalent + to `silverman` when there is more than 1 value in a group. + cut : float, default=3 Defines the length of the grid past the lowest and highest - values of ``x`` so that the kernel goes to zero. The end points - are ``-/+ cut*bw*{min(x) or max(x)}``. - clip : tuple, optional (default: (-np.inf, np.inf)) - Values in ``x`` that are outside of the range given by clip are - dropped. The number of values in ``x`` is then shortened. + values of `x` so that the kernel goes to zero. The end points + are `-/+ cut*bw*{min(x) or max(x)}`. + clip : tuple, default=(-inf, inf) + Values in `x` that are outside of the range given by clip are + dropped. The number of values in `x` is then shortened. See Also -------- @@ -86,16 +88,16 @@ class stat_density(stat): _aesthetics_doc = """ {aesthetics_table} - .. rubric:: Options for computed aesthetics - - :: + **Options for computed aesthetics** - 'density' # density estimate + ```python + 'density' # density estimate - 'count' # density * number of points, - # useful for stacked density plots + 'count' # density * number of points, + # useful for stacked density plots - 'scaled' # density estimate, scaled to maximum of 1 + 'scaled' # density estimate, scaled to maximum of 1 + ``` """ REQUIRED_AES = {"x"} diff --git a/plotnine/stats/stat_density_2d.py b/plotnine/stats/stat_density_2d.py index 91addf54d..9f3f84531 100644 --- a/plotnine/stats/stat_density_2d.py +++ b/plotnine/stats/stat_density_2d.py @@ -16,20 +16,17 @@ class stat_density_2d(stat): Parameters ---------- {common_parameters} - contour : bool + contour : bool, default=True Whether to create contours of the 2d density estimate. - Default is True. - n : int, optional(default: 64) + n : int, default=64 Number of equally spaced points at which the density is to be estimated. For efficient computation, it should be a power of two. - levels : int or array_like + levels : int, array_like, default=5 Contour levels. If an integer, it specifies the maximum number - of levels, if array_like it is the levels themselves. Default - is 5. - package : str in ``['statsmodels', 'scipy', 'sklearn']`` - Package whose kernel density estimation to use. Default is - statsmodels. + of levels, if array_like it is the levels themselves. + package : "statsmodels", "scipy", "sklearn", default="statsmodels" + Package whose kernel density estimation to use. kde_params : dict Keyword arguments to pass on to the kde class. @@ -43,13 +40,13 @@ class stat_density_2d(stat): _aesthetics_doc = """ {aesthetics_table} - .. rubric:: Options for computed aesthetics + **Options for computed aesthetics** - :: - - 'level' # density level of a contour - 'density' # Computed density at a point - 'piece' # Numeric id of a contour in a given group + ```python + "level" # density level of a contour + "density" # Computed density at a point + "piece" # Numeric id of a contour in a given group + ``` `level` is only relevant when contours are computed. `density` is available only when no contours are computed. `piece` is diff --git a/plotnine/stats/stat_ecdf.py b/plotnine/stats/stat_ecdf.py index ce80973f2..297146661 100644 --- a/plotnine/stats/stat_ecdf.py +++ b/plotnine/stats/stat_ecdf.py @@ -16,7 +16,7 @@ class stat_ecdf(stat): Parameters ---------- {common_parameters} - n : int (default: None) + n : int, default=None This is the number of points to interpolate with. If :py:`None`, do not interpolate. @@ -28,13 +28,12 @@ class stat_ecdf(stat): _aesthetics_doc = """ {aesthetics_table} - .. rubric:: Options for computed aesthetics - - :: - - 'x' # x in the data - 'ecdf' # cumulative density corresponding to x + **Options for computed aesthetics** + ```python + "x" # x in the data + "ecdf" # cumulative density corresponding to x + ``` """ REQUIRED_AES = {"x"} diff --git a/plotnine/stats/stat_ellipse.py b/plotnine/stats/stat_ellipse.py index fa778200d..aea5c4ed0 100644 --- a/plotnine/stats/stat_ellipse.py +++ b/plotnine/stats/stat_ellipse.py @@ -26,18 +26,17 @@ class stat_ellipse(stat): Parameters ---------- {common_parameters} - type : str in ['t', 'norm', 'euclid'] (default: 't') + type : "t", "norm", "euclid", default="t" The type of ellipse. - - ``'t'`` - assumes a multivariate t-distribution, and - - ``'norm'`` - assumes a multivariate normal distribution. - - ``'euclid'`` - draws a circle with the radius equal to - `level`, representing the euclidean distance from the - center. + - `t` - assumes a multivariate t-distribution, and + - `norm` - assumes a multivariate normal distribution. + - `euclid` - draws a circle with the radius equal to + `level`, representing the euclidean distance from the center. - level : float, optional (default: 0.95) + level : float, default=0.95 The confidence level at which to draw the ellipse. - segments : int, optional (default: 51) + segments : int, ptional (default=51 Number of segments to be used in drawing the ellipse. """ @@ -121,7 +120,7 @@ def cov_trob( breakdown point. **credit**: This function a port of the R function - ``MASS::cov.trob``. + `MASS::cov.trob`. Parameters ---------- @@ -129,15 +128,15 @@ def cov_trob( data matrix. Missing values (NaNs) are not allowed. wt : array A vector of weights for each case: these are treated as - if the case i actually occurred ``wt[i]`` times. + if the case i actually occurred `wt[i]` times. cor : bool Flag to choose between returning the correlation (``cor=True``) or covariance (``cor=False``) matrix. center : array or bool A logical value or a numeric vector providing the location about which the covariance is to be taken. - If ``center=False``, no centering is done; if - ``center=True`` the MLE of the location vector is used. + If `center=False`, no centering is done; if + `center=True` the MLE of the location vector is used. nu : int 'degrees of freedom' for the multivariate t distribution. Must exceed 2 (so that the covariance matrix is finite). @@ -151,15 +150,15 @@ def cov_trob( out : dict A dictionary with with the following key-value - - ``cov`` : the fitted covariance matrix. - - ``center`` : the estimated or specified location vector. - - ``wt`` : the specified weights: only returned if the + - `cov` : the fitted covariance matrix. + - `center` : the estimated or specified location vector. + - `wt` : the specified weights: only returned if the wt argument was given. - - ``n_obs`` : the number of cases used in the fitting. - - ``cor`` : the fitted correlation matrix: only returned - if ``cor=True``. - - ``call`` : The matched call. - - ``iter`` : The number of iterations used. + - `n_obs` : the number of cases used in the fitting. + - `cor` : the fitted correlation matrix: only returned + if `cor=True`. + - `call` : The matched call. + - `iter` : The number of iterations used. References ---------- diff --git a/plotnine/stats/stat_function.py b/plotnine/stats/stat_function.py index 318c1d29a..d0d9d649e 100644 --- a/plotnine/stats/stat_function.py +++ b/plotnine/stats/stat_function.py @@ -29,25 +29,26 @@ class stat_function(stat): {common_parameters} fun : function Function to evaluate. - n : int, optional (default: 101) + n : int, default=101 Number of points at which to evaluate the function. - xlim : tuple (default: None) - ``x`` limits for the range. The default depends on - the ``x`` aesthetic. There is not an ``x`` aesthetic - then the ``xlim`` must be provided. - args : tuple or dict (default: None) - Arguments to pass to ``fun``. + xlim : tuple, default=None + `x` limits for the range. The default depends on + the `x` aesthetic. There is not an `x` aesthetic + then the `xlim` must be provided. + args : tuple, dict, default=None + Arguments to pass to `fun`. """ _aesthetics_doc = """ {aesthetics_table} - .. rubric:: Options for computed aesthetics + **Options for computed aesthetics** - :: + ```python + 'x' # x points at which the function is evaluated + 'fx' # points evaluated at each x + ``` - 'x' # x points at which the function is evaluated - 'fx' # points evaluated at each x """ DEFAULT_PARAMS = { diff --git a/plotnine/stats/stat_hull.py b/plotnine/stats/stat_hull.py index db2a8405d..5a27a966d 100644 --- a/plotnine/stats/stat_hull.py +++ b/plotnine/stats/stat_hull.py @@ -15,7 +15,7 @@ class stat_hull(stat): Parameters ---------- {common_parameters} - qhull_options: str, optional + qhull_options: str, default=None Additional options to pass to Qhull. See `Qhull `__ documentation for details. @@ -31,11 +31,11 @@ class stat_hull(stat): _aesthetics_doc = """ {aesthetics_table} - .. rubric:: Options for computed aesthetics + **Options for computed aesthetics** - :: - - 'area' # Area of the convex hull + ```python + "area" # Area of the convex hull + ``` """ REQUIRED_AES = {"x", "y"} diff --git a/plotnine/stats/stat_pointdensity.py b/plotnine/stats/stat_pointdensity.py index 2f54044de..1da7c48ca 100644 --- a/plotnine/stats/stat_pointdensity.py +++ b/plotnine/stats/stat_pointdensity.py @@ -17,10 +17,9 @@ class stat_pointdensity(stat): Parameters ---------- {common_parameters} - package : str in ``['statsmodels', 'scipy', 'sklearn']`` - Package whose kernel density estimation to use. Default is - statsmodels. - kde_params : dict + package : "statsmodels", "scipy", "sklearn", default="statsmodels" + Package whose kernel density estimation to use. + kde_params : dict, default=None Keyword arguments to pass on to the kde class. See Also @@ -33,11 +32,11 @@ class stat_pointdensity(stat): _aesthetics_doc = """ {aesthetics_table} - .. rubric:: Options for computed aesthetics + **Options for computed aesthetics** - :: - - 'density' # Computed density at a point + ```python + "density" # Computed density at a point + ``` """ REQUIRED_AES = {"x", "y"} diff --git a/plotnine/stats/stat_qq.py b/plotnine/stats/stat_qq.py index b2ec20dc2..1601d6169 100644 --- a/plotnine/stats/stat_qq.py +++ b/plotnine/stats/stat_qq.py @@ -18,40 +18,39 @@ class stat_qq(stat): Parameters ---------- {common_parameters} - distribution : str (default: norm) + distribution : str, default="norm" Distribution or distribution function name. The default is *norm* for a normal probability plot. Objects that look enough like a stats.distributions instance (i.e. they have a ppf method) are also accepted. See :mod:`scipy stats ` for available distributions. - dparams : dict + dparams : dict, default=None Distribution-specific shape parameters (shape parameters plus location and scale). - quantiles : array_like, optional + quantiles : array_like, default=None Probability points at which to calculate the theoretical quantile values. If provided, must be the same number as as the sample data points. The default is to use calculated - theoretical points, use to ``alpha_beta`` control how + theoretical points, use to `alpha_beta` control how these points are generated. - alpha_beta : tuple + alpha_beta : tuple, default=(3/8, 3/8) Parameter values to use when calculating the quantiles. - Default is :py:`(3/8, 3/8)`. See Also -------- - scipy.stats.mstats.plotting_positions : Uses ``alpha_beta`` + scipy.stats.mstats.plotting_positions : Uses `alpha_beta` to calculate the quantiles. """ _aesthetics_doc = """ {aesthetics_table} - .. rubric:: Options for computed aesthetics + **Options for computed aesthetics** - :: - - 'theoretical' # theoretical quantiles - 'sample' # sample quantiles + ```python + 'theoretical' # theoretical quantiles + 'sample' # sample quantiles + ``` """ REQUIRED_AES = {"sample"} diff --git a/plotnine/stats/stat_qq_line.py b/plotnine/stats/stat_qq_line.py index f49ce8dc2..cb08e5dc4 100644 --- a/plotnine/stats/stat_qq_line.py +++ b/plotnine/stats/stat_qq_line.py @@ -17,33 +17,31 @@ class stat_qq_line(stat): Parameters ---------- {common_parameters} - distribution : str (default: norm) + distribution : str, default="norm" Distribution or distribution function name. The default is *norm* for a normal probability plot. Objects that look enough like a stats.distributions instance (i.e. they have a ppf method) are also accepted. See :mod:`scipy stats ` for available distributions. - dparams : dict, optional + dparams : dict, default=None Distribution-specific shape parameters (shape parameters plus location and scale). - quantiles : array_like, optional + quantiles : array_like, default=None Probability points at which to calculate the theoretical quantile values. If provided, must be the same number as as the sample data points. The default is to use calculated - theoretical points, use to ``alpha_beta`` control how + theoretical points, use to `alpha_beta` control how these points are generated. - alpha_beta : tuple + alpha_beta : tuple, default=(3/8, 3/8) Parameter values to use when calculating the quantiles. - Default is :py:`(3/8, 3/8)`. - line_p : tuple, optional + line_p : tuple, default=(0.25, 0.75) Quantiles to use when fitting a Q-Q line. Must be 2 values. - Default is :py:`(0.25, 0.75)`. - fullrange : bool - If :py:`True` the fit will span the full range of the plot. + fullrange : bool, default=False + If `True`{.py} the fit will span the full range of the plot. See Also -------- - scipy.stats.mstats.plotting_positions : Uses ``alpha_beta`` + scipy.stats.mstats.plotting_positions : Uses `alpha_beta` to calculate the quantiles. """ diff --git a/plotnine/stats/stat_quantile.py b/plotnine/stats/stat_quantile.py index fc874155f..30077d75a 100644 --- a/plotnine/stats/stat_quantile.py +++ b/plotnine/stats/stat_quantile.py @@ -19,11 +19,11 @@ class stat_quantile(stat): Parameters ---------- {common_parameters} - quantiles : tuple, optional (default: (0.25, 0.5, 0.75)) + quantiles : tuple, default=(0.25, 0.5, 0.75) Quantiles of y to compute - formula : str, optional (default: 'y ~ x') + formula : str, default="y ~ x" Formula relating y variables to x variables - method_args : dict, optional + method_args : dict, default=None Extra arguments passed on to the model fitting method, :meth:`statsmodels.regression.quantile_regression.QuantReg.fit`. @@ -36,15 +36,15 @@ class stat_quantile(stat): _aesthetics_doc = """ {aesthetics_table} - .. rubric:: Options for computed aesthetics + **Options for computed aesthetics** - :: - - 'quantile' # quantile - 'group' # group identifier + ```python + "quantile" # quantile + "group" # group identifier + ``` Calculated aesthetics are accessed using the `after_stat` function. - e.g. :py:`after_stat('quantile')`. + e.g. `after_stat('quantile')`{.py}. """ REQUIRED_AES = {"x", "y"} diff --git a/plotnine/stats/stat_sina.py b/plotnine/stats/stat_sina.py index 4b3e8003b..ad6275a2c 100644 --- a/plotnine/stats/stat_sina.py +++ b/plotnine/stats/stat_sina.py @@ -21,50 +21,43 @@ class stat_sina(stat): Parameters ---------- {common_parameters} - binwidth : float + binwidth : float, default=None The width of the bins. The default is to use bins that cover the range of the data. You should always override this value, exploring multiple widths to find the best to illustrate the stories in your data. - bins : int (default: 50) + bins : int, default=50 Number of bins. Overridden by binwidth. - method : 'density' or 'counts' + method : "density", "counts", default="density" Choose the method to spread the samples within the same bin along the x-axis. Available methods: "density", "counts" (can be abbreviated, e.g. "d"). See Details. - maxwidth : float + maxwidth : float, default=None Control the maximum width the points can spread into. Values should be in the range (0, 1). - adjust : float, optional (default: 1) + adjust : float, default=1 Adjusts the bandwidth of the density kernel when - ``method='density'`` (see density). - bw : str or float, optional (default: 'nrd0') + `method="density"`. see [](`~plotnine.stats.stat_density`). + bw : str, float, default="nrd0" The bandwidth to use, If a float is given, it is the bandwidth. - The :py:`str` choices are:: + The `str`{.py} choices are: + `"nrd0", "normal_reference", "scott", "silverman"`{.py} - 'nrd0' - 'normal_reference' - 'scott' - 'silverman' - - ``nrd0`` is a port of ``stats::bw.nrd0`` in R; it is eqiuvalent - to ``silverman`` when there is more than 1 value in a group. - bin_limit : int (default: 1) + `nrd0` is a port of `stats::bw.nrd0` in R; it is eqiuvalent + to `silverman` when there is more than 1 value in a group. + bin_limit : int, default=1 If the samples within the same y-axis bin are more than `bin_limit`, the samples's X coordinates will be adjusted. - This parameter is effective only when :py:`method='counts'` - random_state : int or ~numpy.random.RandomState, optional - Seed or Random number generator to use. If ``None``, then + This parameter is effective only when `method='counts'`{.py} + random_state : int, ~numpy.random.RandomState, default=None + Seed or Random number generator to use. If `None`, then numpy global generator :class:`numpy.random` is used. - scale : str (default: area) - How to scale the sina groups. The options are:: - - 'area' # Scale by the largest density/bin amoung the different - # sinas + scale : "area", "count", "width", default="area" + How to scale the sina groups. - 'count' # areas are scaled proportionally to the number of points - - 'width' # Only scale according to the maxwidth parameter. + - `area` - Scale by the largest density/bin among the different sinas + - `count` - areas are scaled proportionally to the number of points + - `width` - Only scale according to the maxwidth parameter. See Also -------- @@ -74,15 +67,15 @@ class stat_sina(stat): _aesthetics_doc = """ {aesthetics_table} - .. rubric:: Options for computed aesthetics - - :: + **Options for computed aesthetics** - 'quantile' # quantile - 'group' # group identifier + ```python + "quantile" # quantile + "group" # group identifier + ``` Calculated aesthetics are accessed using the `after_stat` function. - e.g. :py:`after_stat('quantile')`. + e.g. `after_stat('quantile')`{.py}. """ REQUIRED_AES = {"x", "y"} diff --git a/plotnine/stats/stat_smooth.py b/plotnine/stats/stat_smooth.py index 0271c0f1e..eaeae198b 100644 --- a/plotnine/stats/stat_smooth.py +++ b/plotnine/stats/stat_smooth.py @@ -19,87 +19,89 @@ class stat_smooth(stat): Parameters ---------- {common_parameters} - - method : str or callable, optional (default: 'auto') + method : str, callable, default="auto" The available methods are:: - - 'auto' # Use loess if (n<1000), glm otherwise - 'lm', 'ols' # Linear Model - 'wls' # Weighted Linear Model - 'rlm' # Robust Linear Model - 'glm' # Generalized linear Model - 'gls' # Generalized Least Squares - 'lowess' # Locally Weighted Regression (simple) - 'loess' # Locally Weighted Regression - 'mavg' # Moving Average - 'gpr' # Gaussian Process Regressor - - If a `callable` is passed, it must have the signature:: - - def my_smoother(data, xseq, **params): - # * data - has the x and y values for the model - # * xseq - x values to be predicted - # * params - stat parameters - # - # It must return a new dataframe. Below is the - # template used internally by Plotnine - - # Input data into the model - x, y = data['x'], data['y'] - - # Create and fit a model - model = Model(x, y) - results = Model.fit() - - # Create output data by getting predictions on - # the xseq values - data = pd.DataFrame({ - 'x': xseq, - 'y': results.predict(xseq)}) - - # Compute confidence intervals, this depends on - # the model. However, given standard errors and the - # degrees of freedom we can compute the confidence - # intervals using the t-distribution. - # - # For an alternative, implement confidence interals by - # the bootstrap method - if params['se']: - from plotnine.utils.smoothers import tdist_ci - y = data['y'] # The predicted value - df = 123 # Degrees of freedom - stderr = results.stderr # Standard error - level = params['level'] # The parameter value - low, high = tdist_ci(y, df, stderr, level) - data['se'] = stderr - data['ymin'] = low - data['ymax'] = high - - return data + ```python + "auto" # Use loess if (n<1000), glm otherwise + "lm", "ols" # Linear Model + "wls" # Weighted Linear Model + "rlm" # Robust Linear Model + "glm" # Generalized linear Model + "gls" # Generalized Least Squares + "lowess" # Locally Weighted Regression (simple) + "loess" # Locally Weighted Regression + "mavg" # Moving Average + "gpr" # Gaussian Process Regressor + ``` + + If a `callable` is passed, it must have the signature: + + ```python + def my_smoother(data, xseq, **params): + # * data - has the x and y values for the model + # * xseq - x values to be predicted + # * params - stat parameters + # + # It must return a new dataframe. Below is the + # template used internally by Plotnine + + # Input data into the model + x, y = data["x"], data["y"] + + # Create and fit a model + model = Model(x, y) + results = Model.fit() + + # Create output data by getting predictions on + # the xseq values + data = pd.DataFrame({ + "x": xseq, + "y": results.predict(xseq)}) + + # Compute confidence intervals, this depends on + # the model. However, given standard errors and the + # degrees of freedom we can compute the confidence + # intervals using the t-distribution. + # + # For an alternative, implement confidence interals by + # the bootstrap method + if params["se"]: + from plotnine.utils.smoothers import tdist_ci + y = data["y"] # The predicted value + df = 123 # Degrees of freedom + stderr = results.stderr # Standard error + level = params["level"] # The parameter value + low, high = tdist_ci(y, df, stderr, level) + data["se"] = stderr + data["ymin"] = low + data["ymax"] = high + + return data + ``` For *loess* smoothing you must install the `scikit-misc` package. - You can install it using with ``pip install scikit-misc`` or - ``pip install plotnine[all]``. - formula : formula_like + You can install it using with `pip install scikit-misc` or + `pip install plotnine[all]`. + formula : formula_like, default=None An object that can be used to construct a patsy design matrix. - This is usually a string. You can only use a formula if ``method`` + This is usually a string. You can only use a formula if `method` is one of *lm*, *ols*, *wls*, *glm*, *rlm* or *gls*, and in the - :ref:`formula ` you may refer to the ``x`` and - ``y`` aesthetic variables. - se : bool (default: True) - If :py:`True` draw confidence interval around the smooth line. - n : int (default: 80) + :ref:`formula ` you may refer to the `x` and + `y` aesthetic variables. + se : bool, default=True + If `True`{.py} draw confidence interval around the smooth line. + n : int, default=80 Number of points to evaluate the smoother at. Some smoothers like *mavg* do not support this. - fullrange : bool (default: False) - If :py:`True` the fit will span the full range of the plot. - level : float (default: 0.95) - Level of confidence to use if :py:`se=True`. - span : float (default: 2/3.) + fullrange : bool, default: False + If `True`{.py} the fit will span the full range of the plot. + level : float, default=0.95 + Level of confidence to use if `se=True`{.py}. + span : float, default=2/3. Controls the amount of smoothing for the *loess* smoother. Larger number means more smoothing. It should be in the - ``(0, 1)`` range. - method_args : dict (default: {}) + `(0, 1)` range. + method_args : dict, default={} Additional arguments passed on to the modelling method. See Also @@ -125,16 +127,16 @@ def my_smoother(data, xseq, **params): _aesthetics_doc = """ {aesthetics_table} - .. rubric:: Options for computed aesthetics - - :: + **Options for computed aesthetics** - 'se' # Standard error of points in bin - 'ymin' # Lower confidence limit - 'ymax' # Upper confidence limit + ```python + "se" # Standard error of points in bin + "ymin" # Lower confidence limit + "ymax" # Upper confidence limit + ``` Calculated aesthetics are accessed using the `after_stat` function. - e.g. :py:`after_stat('se')`. + e.g. `after_stat('se')`{.py}. """ REQUIRED_AES = {"x", "y"} diff --git a/plotnine/stats/stat_sum.py b/plotnine/stats/stat_sum.py index 9f62b6223..d68cb22bf 100644 --- a/plotnine/stats/stat_sum.py +++ b/plotnine/stats/stat_sum.py @@ -22,13 +22,12 @@ class stat_sum(stat): _aesthetics_doc = """ {aesthetics_table} - .. rubric:: Options for computed aesthetics - - :: - - 'n' # Number of observations at a position - 'prop' # Ratio of points in that panel at a position + **Options for computed aesthetics** + ```python + "n" # Number of observations at a position + "prop" # Ratio of points in that panel at a position + ``` """ REQUIRED_AES = {"x", "y"} diff --git a/plotnine/stats/stat_summary.py b/plotnine/stats/stat_summary.py index f7cf4ccab..43fbd1f36 100644 --- a/plotnine/stats/stat_summary.py +++ b/plotnine/stats/stat_summary.py @@ -50,7 +50,7 @@ def mean_cl_boot( confidence_interval : float Confidence interval in the range (0, 1). random_state : int or ~numpy.random.RandomState, optional - Seed or Random number generator to use. If ``None``, then + Seed or Random number generator to use. If `None`, then numpy global generator :class:`numpy.random` is used. """ return bootstrap_statistics( @@ -190,39 +190,40 @@ class stat_summary(stat): Parameters ---------- {common_parameters} - fun_data : str or function, optional - One of:: - - # Bootstrapped mean, confidence interval - # Arguments: - # n_samples - No. of samples to draw - # confidence_interval - # random_state - 'mean_cl_boot' - - # Mean, C.I. assuming normal distribution - # Arguments: - # confidence_interval - 'mean_cl_normal' - - # Mean, standard deviation * constant - # Arguments: - # mult - multiplication factor - 'mean_sdl' - - # Median, outlier quantiles with equal tail areas - # Arguments: - # confidence_interval - 'median_hilow' - - # Mean, Standard Errors * constant - # Arguments: - # mult - multiplication factor - 'mean_se' + fun_data : str or function, default="mean_cl_boot" + One of: + + ```python + # Bootstrapped mean, confidence interval + # Arguments: + # n_samples - No. of samples to draw + # confidence_interval + # random_state + "mean_cl_boot" + + # Mean, C.I. assuming normal distribution + # Arguments: + # confidence_interval + "mean_cl_normal" + + # Mean, standard deviation * constant + # Arguments: + # mult - multiplication factor + "mean_sdl" + + # Median, outlier quantiles with equal tail areas + # Arguments: + # confidence_interval + "median_hilow" + + # Mean, Standard Errors * constant + # Arguments: + # mult - multiplication factor + "mean_se" + ``` or any function that takes a array and returns a dataframe - with three columns named ``y``, ``ymin`` and ``ymax``. - Defaults to :py:`'mean_cl_boot'`. + with three columns named `y`, `ymin` and `ymax`. fun_y : function, optional (default: None) Any function that takes a array-like and returns a value fun_ymin : function (default:None) @@ -236,13 +237,13 @@ class stat_summary(stat): a conflict, create a wrapper function that resolves the ambiguity in the argument names. random_state : int or ~numpy.random.RandomState, optional - Seed or Random number generator to use. If ``None``, then + Seed or Random number generator to use. If `None`, then numpy global generator :class:`numpy.random` is used. Notes ----- - If any of ``fun_y``, ``fun_ymin`` or ``fun_ymax`` are provided, the - value of ``fun_data`` will be ignored. + If any of `fun_y`, `fun_ymin` or `fun_ymax` are provided, the + value of `fun_data` will be ignored. See Also -------- @@ -252,15 +253,15 @@ class stat_summary(stat): _aesthetics_doc = """ {aesthetics_table} - .. rubric:: Options for computed aesthetics + **Options for computed aesthetics** - :: - - 'ymin' # ymin computed by the summary function - 'ymax' # ymax computed by the summary function + ```python + "ymin" # ymin computed by the summary function + "ymax" # ymax computed by the summary function + ``` Calculated aesthetics are accessed using the `after_stat` function. - e.g. :py:`after_stat('ymin')`. + e.g. `after_stat('ymin')`{.py}. """ REQUIRED_AES = {"x", "y"} diff --git a/plotnine/stats/stat_summary_bin.py b/plotnine/stats/stat_summary_bin.py index 77b113b46..4e78bb4f9 100644 --- a/plotnine/stats/stat_summary_bin.py +++ b/plotnine/stats/stat_summary_bin.py @@ -28,20 +28,20 @@ class stat_summary_bin(stat): bins : int or tuple, optional (default: 30) Number of bins. Overridden by binwidth. breaks : array-like(s), optional (default: None) - Bin boundaries. This supercedes the ``binwidth``, ``bins`` - and ``boundary`` arguments. + Bin boundaries. This supercedes the `binwidth`, `bins` + and `boundary` arguments. boundary : float or tuple, optional (default: None) A boundary between two bins. As with center, things are shifted when boundary is outside the range of the data. - For example, to center on integers, use :py:`width=1` and - :py:`boundary=0.5`, even if 1 is outside the range of the + For example, to center on integers, use `width=1`{.py} and + `boundary=0.5`{.py}, even if 1 is outside the range of the data. At most one of center and boundary may be specified. fun_data : str or function, optional One of - :py:`['mean_cl_boot', 'mean_cl_normal', 'mean_sdl', 'median_hilow', - 'mean_se']` or any function that takes a array and returns a - dataframe with three rows indexed as ``y``, ``ymin`` and ``ymax``. - Defaults to :py:`'mean_se'`. + `['mean_cl_boot', 'mean_cl_normal', 'mean_sdl', 'median_hilow', + 'mean_se']`{.py} or any function that takes a array and returns a + dataframe with three rows indexed as `y`, `ymin` and `ymax`. + Defaults to `'mean_se'`{.py}. fun_y : function, optional (default: None) Any function that takes an array-like and returns a single value fun_ymax : function, optional (default: None) @@ -53,7 +53,7 @@ class stat_summary_bin(stat): a conflict, create a wrapper function that resolves the ambiguity in the argument names. random_state : int or ~numpy.random.RandomState, optional - Seed or Random number generator to use. If ``None``, then + Seed or Random number generator to use. If `None`, then numpy global generator :class:`numpy.random` is used. Notes @@ -70,17 +70,17 @@ class stat_summary_bin(stat): _aesthetics_doc = """ {aesthetics_table} - .. rubric:: Options for computed aesthetics + **Options for computed aesthetics** - :: - - 'bin' # bin identifier - 'width' # bin width - 'ymin' # ymin computed by the summary function - 'ymax' # ymax computed by the summary function + ```python + "bin" # bin identifier + "width" # bin width + "ymin" # ymin computed by the summary function + "ymax" # ymax computed by the summary function + ``` Calculated aesthetics are accessed using the `after_stat` function. - e.g. :py:`after_stat('ymin')`. + e.g. `after_stat('ymin')`{.py}. """ REQUIRED_AES = {"x", "y"} diff --git a/plotnine/stats/stat_ydensity.py b/plotnine/stats/stat_ydensity.py index 8200560bc..907a19f65 100644 --- a/plotnine/stats/stat_ydensity.py +++ b/plotnine/stats/stat_ydensity.py @@ -20,26 +20,27 @@ class stat_ydensity(stat): ---------- {common_parameters} kernel : str, optional (default: 'gaussian') - Kernel used for density estimation. One of:: - - 'biweight' - 'cosine' - 'cosine2' - 'epanechnikov' - 'gaussian' - 'triangular' - 'triweight' - 'uniform' - + Kernel used for density estimation. One of: + + ```python + "biweight" + "cosine" + "cosine2" + "epanechnikov" + "gaussian" + "triangular" + "triweight" + "uniform" + ``` adjust : float, optional (default: 1) - An adjustment factor for the ``bw``. Bandwidth becomes - :py:`bw * adjust`. + An adjustment factor for the `bw`. Bandwidth becomes + `bw * adjust`{.py}. Adjustment of the bandwidth. trim : bool, optional (default: False) This parameter only matters if you are displaying multiple - densities in one plot. If :py:`False`, the default, each + densities in one plot. If `False`{.py}, the default, each density is computed on the full range of the data. If - :py:`True`, each density is computed over the range of that + `True`{.py}, each density is computed over the range of that group; this typically means the estimated x values will not line-up, and hence you won't be able to stack density values. n : int, optional(default: 1024) @@ -48,24 +49,31 @@ class stat_ydensity(stat): of two. bw : str or float, optional (default: 'nrd0') The bandwidth to use, If a float is given, it is the bandwidth. - The :py:`str` choices are:: + The `str` choices are: - 'normal_reference' - 'scott' - 'silverman' + ```python + "normal_reference" + "scott" + "silverman" + ``` - ``nrd0`` is a port of ``stats::bw.nrd0`` in R; it is eqiuvalent - to ``silverman`` when there is more than 1 value in a group. + `nrd0` is a port of `stats::bw.nrd0` in R; it is eqiuvalent + to `silverman` when there is more than 1 value in a group. scale : (default: area) - How to scale the violins. The options are:: + How to scale the violins. The options are: - 'area' # all violins have the same area, before - # trimming the tails. + ```python + # all violins have the same area, before + # trimming the tails. + "area" - 'count' # areas are scaled proportionally to the number - # of observations. + # areas are scaled proportionally to the number + # of observations. + "count" - 'width' # all violins have the same maximum width. + # all violins have the same maximum width. + "width" + ``` See Also -------- @@ -77,15 +85,15 @@ class stat_ydensity(stat): _aesthetics_doc = """ {aesthetics_table} - .. rubric:: Options for computed aesthetics - - :: + **Options for computed aesthetics** - 'width' # Maximum width of density, [0, 1] range. - 'violinwidth' # Shape of the violin + ```python + "width" # Maximum width of density, [0, 1] range. + "violinwidth" # Shape of the violin + ``` Calculated aesthetics are accessed using the `after_stat` function. - e.g. :py:`after_stat('width')`. + e.g. `after_stat('width')`{.py}. """ REQUIRED_AES = {"x", "y"} NON_MISSING_AES = {"weight"} diff --git a/plotnine/themes/elements.py b/plotnine/themes/elements.py index 118ee5dbb..5d96a5277 100644 --- a/plotnine/themes/elements.py +++ b/plotnine/themes/elements.py @@ -169,11 +169,11 @@ class element_text(element_base): Background color margin : dict Margin around the text. The keys are one of - ``['t', 'b', 'l', 'r']`` and ``units``. The units are + ``['t', 'b', 'l', 'r']`` and `units`. The units are one of ``['pt', 'lines', 'in']``. The *units* default - to ``pt`` and the other keys to ``0``. Not all text + to `pt` and the other keys to `0`. Not all text themeables support margin parameters and other than the - ``units``, only some of the other keys may apply. + `units`, only some of the other keys may apply. kwargs : dict Parameters recognised by :class:`matplotlib.text.Text` diff --git a/plotnine/themes/seaborn_rcmod.py b/plotnine/themes/seaborn_rcmod.py index 8322599b5..2932f2077 100644 --- a/plotnine/themes/seaborn_rcmod.py +++ b/plotnine/themes/seaborn_rcmod.py @@ -26,6 +26,7 @@ class dummy: """ No Op """ + __version__ = _mpl.__version__ rcParams = {} @@ -34,47 +35,36 @@ class dummy: _style_keys = [ - "axes.facecolor", "axes.edgecolor", "axes.grid", "axes.axisbelow", "axes.labelcolor", - "figure.facecolor", - "grid.color", "grid.linestyle", - "text.color", - "xtick.color", "ytick.color", "xtick.direction", "ytick.direction", "lines.solid_capstyle", - "patch.edgecolor", "patch.force_edgecolor", - "image.cmap", "font.family", "font.sans-serif", - "xtick.bottom", "xtick.top", "ytick.left", "ytick.right", - "axes.spines.left", "axes.spines.bottom", "axes.spines.right", "axes.spines.top", - ] _context_keys = [ - "font.size", "axes.labelsize", "axes.titlesize", @@ -82,28 +72,31 @@ class dummy: "ytick.labelsize", "legend.fontsize", "legend.title_fontsize", - "axes.linewidth", "grid.linewidth", "lines.linewidth", "lines.markersize", "patch.linewidth", - "xtick.major.width", "ytick.major.width", "xtick.minor.width", "ytick.minor.width", - "xtick.major.size", "ytick.major.size", "xtick.minor.size", "ytick.minor.size", - ] -def set_theme(context="notebook", style="darkgrid", palette="deep", - font="sans-serif", font_scale=1, color_codes=False, rc=None): +def set_theme( + context="notebook", + style="darkgrid", + palette="deep", + font="sans-serif", + font_scale=1, + color_codes=False, + rc=None, +): """ Set aesthetic parameters in one step @@ -124,7 +117,7 @@ def set_theme(context="notebook", style="darkgrid", palette="deep", Separate scaling factor to independently scale the size of the font elements. color_codes : bool - If ``True`` and ``palette`` is a seaborn palette, remap the shorthand + If `True` and `palette` is a seaborn palette, remap the shorthand color codes (e.g. "b", "g", "r", etc.) to the colors from this palette. rc : dict or None Dictionary of rc parameter mappings to override the above. @@ -153,7 +146,7 @@ def axes_style(style=None, rc=None): This affects things like the color of the axes, whether a grid is enabled by default, and other aesthetic elements. - This function returns an object that can be used in a ``with`` statement + This function returns an object that can be used in a `with` statement to temporarily change the style parameters. Parameters @@ -200,100 +193,100 @@ def axes_style(style=None, rc=None): # Common parameters style_dict = { - "figure.facecolor": "white", "axes.labelcolor": dark_gray, - "xtick.direction": "out", "ytick.direction": "out", "xtick.color": dark_gray, "ytick.color": dark_gray, - "axes.axisbelow": True, "grid.linestyle": "-", - - "text.color": dark_gray, "font.family": ["sans-serif"], - "font.sans-serif": ["Arial", "DejaVu Sans", "Liberation Sans", - "Bitstream Vera Sans", "sans-serif"], - - + "font.sans-serif": [ + "Arial", + "DejaVu Sans", + "Liberation Sans", + "Bitstream Vera Sans", + "sans-serif", + ], "lines.solid_capstyle": "round", "patch.edgecolor": "w", "patch.force_edgecolor": True, - "image.cmap": "Greys", - "xtick.top": False, "ytick.right": False, - } # Set grid on or off if "grid" in style: - style_dict.update({ - "axes.grid": True, - }) + style_dict.update( + { + "axes.grid": True, + } + ) else: - style_dict.update({ - "axes.grid": False, - }) + style_dict.update( + { + "axes.grid": False, + } + ) # Set the color of the background, spines, and grids if style.startswith("dark"): - style_dict.update({ - - "axes.facecolor": "#EAEAF2", - "axes.edgecolor": "white", - "grid.color": "white", - - "axes.spines.left": True, - "axes.spines.bottom": True, - "axes.spines.right": True, - "axes.spines.top": True, - - }) + style_dict.update( + { + "axes.facecolor": "#EAEAF2", + "axes.edgecolor": "white", + "grid.color": "white", + "axes.spines.left": True, + "axes.spines.bottom": True, + "axes.spines.right": True, + "axes.spines.top": True, + } + ) elif style == "whitegrid": - style_dict.update({ - - "axes.facecolor": "white", - "axes.edgecolor": light_gray, - "grid.color": light_gray, - - "axes.spines.left": True, - "axes.spines.bottom": True, - "axes.spines.right": True, - "axes.spines.top": True, - - }) + style_dict.update( + { + "axes.facecolor": "white", + "axes.edgecolor": light_gray, + "grid.color": light_gray, + "axes.spines.left": True, + "axes.spines.bottom": True, + "axes.spines.right": True, + "axes.spines.top": True, + } + ) elif style in ["white", "ticks"]: - style_dict.update({ - - "axes.facecolor": "white", - "axes.edgecolor": dark_gray, - "grid.color": light_gray, - - "axes.spines.left": True, - "axes.spines.bottom": True, - "axes.spines.right": True, - "axes.spines.top": True, - - }) + style_dict.update( + { + "axes.facecolor": "white", + "axes.edgecolor": dark_gray, + "grid.color": light_gray, + "axes.spines.left": True, + "axes.spines.bottom": True, + "axes.spines.right": True, + "axes.spines.top": True, + } + ) # Show or hide the axes ticks if style == "ticks": - style_dict.update({ - "xtick.bottom": True, - "ytick.left": True, - }) + style_dict.update( + { + "xtick.bottom": True, + "ytick.left": True, + } + ) else: - style_dict.update({ - "xtick.bottom": False, - "ytick.left": False, - }) + style_dict.update( + { + "xtick.bottom": False, + "ytick.left": False, + } + ) # Remove entries that are not defined in the base list of valid keys # This lets us handle matplotlib <=/> 2.0 @@ -334,7 +327,7 @@ def set_style(style=None, rc=None): See Also -------- - axes_style : return a dict of parameters or use in a ``with`` statement + axes_style : return a dict of parameters or use in a `with` statement to temporarily set the style. set_context : set parameters to scale plot elements set_palette : set the default color palette for figures @@ -354,7 +347,7 @@ def plotting_context(context=None, font_scale=1, rc=None): which are version of the notebook parameters scaled by .8, 1.3, and 1.6, respectively. - This function returns an object that can be used in a ``with`` statement + This function returns an object that can be used in a `with` statement to temporarily change the context parameters. Parameters @@ -395,14 +388,12 @@ def plotting_context(context=None, font_scale=1, rc=None): context_dict = context else: - contexts = ["paper", "notebook", "talk", "poster"] if context not in contexts: raise ValueError("context must be in %s" % ", ".join(contexts)) # Set up dictionary of default parameters texts_base_context = { - "font.size": 12, "axes.labelsize": 12, "axes.titlesize": 12, @@ -410,32 +401,29 @@ def plotting_context(context=None, font_scale=1, rc=None): "ytick.labelsize": 11, "legend.fontsize": 11, "legend.title_fontsize": 12, - } base_context = { - "axes.linewidth": 1.25, "grid.linewidth": 1, "lines.linewidth": 1.5, "lines.markersize": 6, "patch.linewidth": 1, - "xtick.major.width": 1.25, "ytick.major.width": 1.25, "xtick.minor.width": 1, "ytick.minor.width": 1, - "xtick.major.size": 6, "ytick.major.size": 6, "xtick.minor.size": 4, "ytick.minor.size": 4, - } base_context.update(texts_base_context) # Scale all the parameters by the same factor depending on the context - scaling = {"paper": .8, "notebook": 1, "talk": 1.5, "poster": 2}[context] + scaling = {"paper": 0.8, "notebook": 1, "talk": 1.5, "poster": 2}[ + context + ] context_dict = {k: v * scaling for k, v in base_context.items()} # Now independently scale the fonts @@ -487,7 +475,7 @@ def set_context(context=None, font_scale=1, rc=None): See Also -------- plotting_context : return a dictionary of rc parameters, or use in - a ``with`` statement to temporarily set the context. + a `with` statement to temporarily set the context. set_style : set the default parameters for figure style set_palette : set the default color palette for figures @@ -510,16 +498,19 @@ def __call__(self, func): def wrapper(*args, **kwargs): with self: return func(*args, **kwargs) + return wrapper class _AxesStyle(_RCAesthetics): """Light wrapper on a dict to set style temporarily.""" + _keys = _style_keys _set = staticmethod(set_style) class _PlottingContext(_RCAesthetics): """Light wrapper on a dict to set context temporarily.""" + _keys = _context_keys _set = staticmethod(set_context) diff --git a/plotnine/themes/theme.py b/plotnine/themes/theme.py index 4c21d344a..3c954d893 100644 --- a/plotnine/themes/theme.py +++ b/plotnine/themes/theme.py @@ -76,7 +76,7 @@ class theme: ----- When subclassing, make sure to call :python:`theme.__init__`. After which you can customise :python:`self._rcParams` within - the ``__init__`` method of the new theme. The ``rcParams`` + the `__init__` method of the new theme. The `rcParams` should not be modified after that. """ diff --git a/plotnine/themes/theme_538.py b/plotnine/themes/theme_538.py index 02d777430..016abf771 100644 --- a/plotnine/themes/theme_538.py +++ b/plotnine/themes/theme_538.py @@ -9,10 +9,10 @@ class theme_538(theme_gray): Parameters ---------- - base_size : int, optional + base_size : int Base font size. All text sizes are a scaled versions of - the base font size. Default is 11. - base_family : str, optional + the base font size. + base_family : str Base font family. """ diff --git a/plotnine/themes/theme_bw.py b/plotnine/themes/theme_bw.py index f063177f1..fcaebfb15 100644 --- a/plotnine/themes/theme_bw.py +++ b/plotnine/themes/theme_bw.py @@ -9,11 +9,11 @@ class theme_bw(theme_gray): Parameters ---------- - base_size : int, optional + base_size : int Base font size. All text sizes are a scaled versions of - the base font size. Default is 11. - base_family : str, optional - Base font family. + the base font size. + base_family : str + Base font family. If `None`, use [](`plotnine.options.base_family`). """ def __init__(self, base_size=11, base_family=None): diff --git a/plotnine/themes/theme_classic.py b/plotnine/themes/theme_classic.py index dbbdfe1b6..f6f68a65f 100644 --- a/plotnine/themes/theme_classic.py +++ b/plotnine/themes/theme_classic.py @@ -9,11 +9,11 @@ class theme_classic(theme_bw): Parameters ---------- - base_size : int, optional + base_size : int Base font size. All text sizes are a scaled versions of - the base font size. Default is 11. - base_family : str, optional - Base font family. + the base font size. + base_family : str + Base font family. If `None`, use [](`plotnine.options.base_family`). """ def __init__(self, base_size=11, base_family=None): diff --git a/plotnine/themes/theme_dark.py b/plotnine/themes/theme_dark.py index fab81a029..ddcf238c2 100644 --- a/plotnine/themes/theme_dark.py +++ b/plotnine/themes/theme_dark.py @@ -12,11 +12,11 @@ class theme_dark(theme_gray): Parameters ---------- - base_size : int, optional + base_size : int Base font size. All text sizes are a scaled versions of - the base font size. Default is 11. - base_family : str, optional - Base font family. + the base font size. + base_family : str + Base font family. If `None`, use [](`plotnine.options.base_family`). """ def __init__(self, base_size=11, base_family=None): diff --git a/plotnine/themes/theme_gray.py b/plotnine/themes/theme_gray.py index baff85cfe..5df5e00f7 100644 --- a/plotnine/themes/theme_gray.py +++ b/plotnine/themes/theme_gray.py @@ -12,11 +12,11 @@ class theme_gray(theme): Parameters ---------- - base_size : int, optional + base_size : int Base font size. All text sizes are a scaled versions of - the base font size. Default is 11. - base_family : str, optional - Base font family. + the base font size. + base_family : str + Base font family. If `None`, use [](`plotnine.options.base_family`). """ def __init__(self, base_size=11, base_family=None): diff --git a/plotnine/themes/theme_light.py b/plotnine/themes/theme_light.py index 770896a4b..dbf1de8d1 100644 --- a/plotnine/themes/theme_light.py +++ b/plotnine/themes/theme_light.py @@ -12,11 +12,11 @@ class theme_light(theme_gray): Parameters ---------- - base_size : int, optional + base_size : int Base font size. All text sizes are a scaled versions of - the base font size. Default is 11. - base_family : str, optional - Base font family. + the base font size. + base_family : str + Base font family. If `None`, use [](`plotnine.options.base_family`). """ def __init__(self, base_size=11, base_family=None): diff --git a/plotnine/themes/theme_linedraw.py b/plotnine/themes/theme_linedraw.py index 959d86cc3..b0063bc3a 100644 --- a/plotnine/themes/theme_linedraw.py +++ b/plotnine/themes/theme_linedraw.py @@ -9,11 +9,11 @@ class theme_linedraw(theme_gray): Parameters ---------- - base_size : int, optional + base_size : int Base font size. All text sizes are a scaled versions of - the base font size. Default is 11. - base_family : str, optional - Base font family. + the base font size. + base_family : str + Base font family. If `None`, use [](`plotnine.options.base_family`). """ def __init__(self, base_size=11, base_family=None): diff --git a/plotnine/themes/theme_matplotlib.py b/plotnine/themes/theme_matplotlib.py index 5f085ac2e..e11d6ea54 100644 --- a/plotnine/themes/theme_matplotlib.py +++ b/plotnine/themes/theme_matplotlib.py @@ -12,10 +12,9 @@ class theme_matplotlib(theme): Parameters ---------- - rc : dict, optional - rcParams which should be applied on top of - mathplotlib default. - fname : str, optional + rc : dict + rcParams which should be applied on top of mathplotlib default. + fname : str Filename to a matplotlibrc file use_defaults : bool If `True` (the default) resets the plot setting diff --git a/plotnine/themes/theme_minimal.py b/plotnine/themes/theme_minimal.py index f3fedadc5..285d08d1c 100644 --- a/plotnine/themes/theme_minimal.py +++ b/plotnine/themes/theme_minimal.py @@ -9,11 +9,11 @@ class theme_minimal(theme_bw): Parameters ---------- - base_size : int, optional + base_size : int Base font size. All text sizes are a scaled versions of - the base font size. Default is 11. - base_family : str, optional - Base font family. + the base font size. + base_family : str + Base font family. If `None`, use [](`plotnine.options.base_family`). """ def __init__(self, base_size=11, base_family=None): diff --git a/plotnine/themes/theme_seaborn.py b/plotnine/themes/theme_seaborn.py index ce5ea2fdb..eb5ae69d8 100644 --- a/plotnine/themes/theme_seaborn.py +++ b/plotnine/themes/theme_seaborn.py @@ -14,13 +14,13 @@ class theme_seaborn(theme): Parameters ---------- - style: str in ``['whitegrid', 'darkgrid', 'nogrid', 'ticks']`` + style: "whitegrid", "darkgrid", "nogrid", "ticks" Style of axis background. - context: str in ``['notebook', 'talk', 'paper', 'poster']`` + context: "notebook", "talk", "paper", "poster"]`` Intended context for resulting figures. font : str Font family, see matplotlib font manager. - font_scale : float, optional + font_scale : float Separate scaling factor to independently scale the size of the font elements. """ diff --git a/plotnine/themes/theme_tufte.py b/plotnine/themes/theme_tufte.py index 335049c86..08a47ddf2 100644 --- a/plotnine/themes/theme_tufte.py +++ b/plotnine/themes/theme_tufte.py @@ -7,29 +7,30 @@ class theme_tufte(theme_bw): """ Tufte Maximal Data, Minimal Ink Theme - Theme based on Chapter 6 'Data-Ink Maximization and Graphical + Theme based on Chapter 6 Data-Ink Maximization and Graphical Design of Edward Tufte *The Visual Display of Quantitative Information*. No border, no axis lines, no grids. This theme - works best in combination with :class:`geom_rug()` or - :class:`geom_rangeframe()`. + works best in combination with [](`~plotnine.geoms.geom_rug`). - The default font family is set to 'serif' as he uses serif - fonts for labels in 'The Visual Display of Quantitative - Information'. The serif font used by Tufte in his books is + The default font family is set to "serif" as he uses serif + fonts for labels in _The Visual Display of Quantitative + Information_. The serif font used by Tufte in his books is a variant of Bembo, while the sans serif font is Gill Sans. If these fonts are installed on your system, consider setting them explicitly via the argument `base_family`. Parameters ---------- - base_size : int, optional + base_size : int Base font size. All text sizes are a scaled versions of - the base font size. Default is 11. - base_family : str, optional - Base font family. - ticks: logical, optional - Show axis ticks? + the base font size. + base_family : str + Base font family. If `None`, use [](`plotnine.options.base_family`). + ticks: bool + Whether to show axis ticks. + References + ---------- Tufte, Edward R. (2001) The Visual Display of Quantitative Information, Chapter 6. diff --git a/plotnine/themes/theme_xkcd.py b/plotnine/themes/theme_xkcd.py index e0762149c..1b1213b8c 100644 --- a/plotnine/themes/theme_xkcd.py +++ b/plotnine/themes/theme_xkcd.py @@ -11,24 +11,19 @@ class theme_xkcd(theme_gray): Parameters ---------- - base_size : int, optional + base_size : int Base font size. All text sizes are a scaled versions of - the base font size. Default is 12. - scale : float, optional - The amplitude of the wiggle perpendicular to the line - (in pixels). Default is 1. - length : float, optional + the base font size. + scale : float + The amplitude of the wiggle perpendicular to the line (in pixels) + length : float The length of the wiggle along the line (in pixels). - Default is 100. - randomness : float, optional - The factor by which the length is randomly scaled. - Default is 2. - stroke_size : float, optional + randomness : float + The factor by which the length is randomly scaled. Default is 2. + stroke_size : float Size of the stroke to apply to the lines and text paths. - Default is 4. - stroke_color : str or tuple, optional - Color of the strokes. Default is ``white``. - For no color, use ``'none'``. + stroke_color : str, tuple + Color of the strokes. Use `"none"` for no color. """ def __init__( diff --git a/plotnine/themes/themeable.py b/plotnine/themes/themeable.py index 4800212c5..bddd241be 100644 --- a/plotnine/themes/themeable.py +++ b/plotnine/themes/themeable.py @@ -43,8 +43,8 @@ class themeable(metaclass=RegistryHierarchyMeta): 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 + 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, @@ -53,10 +53,10 @@ class themeable(metaclass=RegistryHierarchyMeta): For example, to implement, - - ``axis_title_x`` - ``x`` axis label (element_text; - inherits from ``axis_title``) - - ``axis_title_y`` - ``y`` axis label (element_text; - inherits from ``axis_title``) + - `axis_title_x` - `x` axis label (element_text; + inherits from `axis_title`) + - `axis_title_y` - `y` axis label (element_text; + inherits from `axis_title`) You would have this implementation: @@ -347,7 +347,7 @@ def is_blank(self, name: str) -> bool: If the *name* is not in the list of themeables then the lookup falls back to inheritance hierarchy. If none of the themeables are in the hierarchy are - present, ``False`` is returned. + present, `False` is returned. Parameters ---------- @@ -1696,10 +1696,10 @@ class axis_ticks_direction_x(themeable): Parameters ---------- - theme_element : str in ``['in', 'out', 'inout']`` - - ``in`` - ticks inside the panel - - ``out`` - ticks outside the panel - - ``inout`` - ticks inside and outside the panel + theme_element : "in", "out", "inout" + - `in` - ticks inside the panel + - `out` - ticks outside the panel + - `inout` - ticks inside and outside the panel """ def apply_ax(self, ax: Axes): @@ -1715,10 +1715,10 @@ class axis_ticks_direction_y(themeable): Parameters ---------- - theme_element : str in ``['in', 'out', 'inout']`` - - ``in`` - ticks inside the panel - - ``out`` - ticks outside the panel - - ``inout`` - ticks inside and outside the panel + theme_element : "in", "out", "inout" + - `in` - ticks inside the panel + - `out` - ticks outside the panel + - `inout` - ticks inside and outside the panel """ def apply_ax(self, ax: Axes): @@ -1734,10 +1734,10 @@ class axis_ticks_direction(axis_ticks_direction_x, axis_ticks_direction_y): Parameters ---------- - theme_element : {'in', 'out', 'inout'} - - ``in`` - ticks inside the panel - - ``out`` - ticks outside the panel - - ``inout`` - ticks inside and outside the panel + theme_element : "in", "out", "inout" + - `in` - ticks inside the panel + - `out` - ticks outside the panel + - `inout` - ticks inside and outside the panel """ @@ -1875,7 +1875,7 @@ class aspect_ratio(themeable): Notes ----- - For a fixed relationship between the ``x`` and ``y`` scales, + For a fixed relationship between the `x` and `y` scales, use [](`~plotnine.coords.coord_fixed`). """ @@ -1919,7 +1919,7 @@ class legend_box(themeable): Parameters ---------- - theme_element : str in ``['vertical', 'horizontal']`` + theme_element : "vertical", "horizontal" Whether to stack up the legends vertically or horizontally. """ @@ -1943,7 +1943,7 @@ class legend_box_just(themeable): Parameters ---------- theme_element : str - One of *left*, *right*, *center*, *top* or *bottom* + One of `["left", "right", "center", "top", "bottom"]`{.py} depending the value of :class:`legend_box`. """ @@ -1954,7 +1954,7 @@ class legend_direction(themeable): Parameters ---------- - theme_element : str in ``['vertical', 'horizontal']`` + theme_element : str in `["vertical", "horizontal"]`{.py} Vertically or horizontally """ @@ -2032,8 +2032,9 @@ class legend_position(themeable): Parameters ---------- theme_element : str or tuple - If a string it should be one of *right*, *left*, *top* - *bottom* or *none*. If a tuple, it should be two floats each + If a string it should be one of + `["right", "left", "top", "bottom", "none"]`{.py} + If a tuple, it should be two floats each in the approximate range [0, 1]. The tuple specifies the location of the legend in screen coordinates. """ @@ -2046,8 +2047,8 @@ class legend_title_align(themeable): Parameters ---------- theme_element : str or tuple - If a string it should be one of *right*, *left*, *center*, - *top* or *bottom*. + If a string it should be one of + `["right", "left", "center", "top", "bottom"]`{.py} """ @@ -2092,7 +2093,7 @@ class strip_align_x(themeable): ---------- theme_element : float Value as a proportion of the strip size. A good value - should be the range :math:`[-1, 0.5]`. A negative value + should be the range `[-1, 0.5]`. A negative value puts the strip inside the axes. A positive value creates a margin between the strip and the axes. `0` puts the strip on top of the panels. @@ -2107,7 +2108,7 @@ class strip_align_y(themeable): ---------- theme_element : float Value as a proportion of the strip size. A good value - should be the range :math:`[-1, 0.5]`. A negative value + should be the range `[-1, 0.5]`. A negative value puts the strip inside the axes. A positive value creates a margin between the strip and the axes. `0` puts the strip exactly beside the panels. @@ -2122,7 +2123,7 @@ class strip_align(strip_align_x, strip_align_y): ---------- theme_element : float Value as a proportion of the strip text size. A good value - should be the range :math:`[-1, 0.5]`. A negative value + should be the range `[-1, 0.5]`. A negative value puts the strip inside the axes and a positive value creates a space between the strip and the axes. """ diff --git a/plotnine/utils.py b/plotnine/utils.py index 2b86d163f..90dee0577 100644 --- a/plotnine/utils.py +++ b/plotnine/utils.py @@ -419,12 +419,12 @@ def jitter(x, factor=1, amount=None, random_state=None): has no effect. amount : float This defines the range ([-amount, amount]) of the jitter to - apply to the values. If `0` then ``amount = factor * z/50``. - If `None` then ``amount = factor * d/5``, where d is about + apply to the values. If `0` then `amount = factor * z/50`. + If `None` then `amount = factor * d/5`, where d is about the smallest difference between `x` values and `z` is the range of the `x` values. random_state : int or ~numpy.random.RandomState, optional - Seed or Random number generator to use. If ``None``, then + Seed or Random number generator to use. If `None`, then numpy global generator :class:`numpy.random` is used. References: @@ -656,14 +656,14 @@ def pivot_apply(df, column, index, func, *args, **kwargs): Function to apply to each column group. It *should* return a single value. *args : tuple - Arguments to ``func`` + Arguments to `func` **kwargs : dict - Keyword arguments to ``func`` + Keyword arguments to `func` Returns ------- out : dataframe - Dataframe with index ``index`` and column ``column`` of + Dataframe with index `index` and column `column` of computed/aggregate values . """ @@ -798,15 +798,15 @@ class RegistryHierarchyMeta(type): The class has gets two properties: - 1. ``_registry`` a dictionary of all the subclasses of the + 1. `_registry` a dictionary of all the subclasses of the base class. The keys are the names of the classes and the values are the class objects. - 2. ``_hierarchy`` a dictionary (default) that holds the + 2. `_hierarchy` a dictionary (default) that holds the inheritance hierarchy of each class. Each key is a class and the value is a list of classes. The first name in the list is that of the key class. - The goal of the ``_hierarchy`` object to facilitate the + The goal of the `_hierarchy` object to facilitate the lookup of themeable properties taking into consideration the inheritance hierarchy. For example if `strip_text_x` inherits from `strip_text` which inherits from `text`, then if a property diff --git a/plotnine/watermark.py b/plotnine/watermark.py index 84a2c05aa..733761cbc 100644 --- a/plotnine/watermark.py +++ b/plotnine/watermark.py @@ -19,13 +19,13 @@ class watermark: Parameters ---------- - filename : str | pathlib.Path + filename : str, pathlib.Path Image file - xo : int, optional - x position offset in pixels. Default is 0. - yo : int, optional - y position offset in pixels. Default is 0. - alpha : float, optional + xo : int + x position offset in pixels. + yo : int + y position offset in pixels. + alpha : float Alpha blending value. kwargs : dict Additional parameters passed to diff --git a/qdoc/_quarto.yml b/qdoc/_quarto.yml index 2689b7c34..a7282e02b 100644 --- a/qdoc/_quarto.yml +++ b/qdoc/_quarto.yml @@ -13,27 +13,31 @@ filters: - interlinks interlinks: - sources: - python: - url: https://docs.python.org/3/ - matplotlib: - url: https://matplotlib.org/stable - numpy: - url: https://numpy.org/doc/stable/ - scipy: - url: https://docs.scipy.org/doc/scipy - statsmodels: - url: https://www.statsmodels.org/stable/ - pandas: - url: https://pandas.pydata.org/pandas-docs/stable/ - sklearn: - url: https://scikit-learn.org/stable/ - skmisc: - url: https://has2k1.github.io/scikit-misc/stable/ - adjustText: - url: https://adjusttext.readthedocs.io/en/latest/ - patsy: - url: https://patsy.readthedocs.io/en/stable + sources: {} + # interlinks are slow + # sources: + # python: + # url: https://docs.python.org/3/ + # matplotlib: + # url: https://matplotlib.org/stable/ + # mizani: + # url: https://mizani.readthedocs.io/stable/ + # numpy: + # url: https://numpy.org/doc/stable/ + # scipy: + # url: https://docs.scipy.org/doc/scipy/ + # statsmodels: + # url: https://www.statsmodels.org/stable/ + # pandas: + # url: https://pandas.pydata.org/pandas-docs/stable/ + # sklearn: + # url: https://scikit-learn.org/stable/ + # skmisc: + # url: https://has2k1.github.io/scikit-misc/stable/ + # adjustText: + # url: https://adjusttext.readthedocs.io/en/latest/ + # patsy: + # url: https://patsy.readthedocs.io/en/stable/ website: title: "plotnine {{< env VERSION >}}" diff --git a/qdoc/tutorials/index.qmd b/qdoc/tutorials/index.qmd index b9278f333..6cbd49962 100644 --- a/qdoc/tutorials/index.qmd +++ b/qdoc/tutorials/index.qmd @@ -1,11 +1,11 @@ # Tutorials -- [a-pyqt5-application](/plotnine-examples/plotnine_examples/tutorials/miscellaneous-a-pyqt5-application.ipynb) -- [altering-colors](/plotnine-examples/plotnine_examples/tutorials/miscellaneous-altering-colors.ipynb) -- [automatic-grouping-insufficient](/plotnine-examples/plotnine_examples/tutorials/miscellaneous-automatic-grouping-insufficient.ipynb) -- [manipulating-date-breaks-and-date-labels](/plotnine-examples/plotnine_examples/tutorials/miscellaneous-manipulating-date-breaks-and-date-labels.ipynb) -- [order-plot-series](/plotnine-examples/plotnine_examples/tutorials/miscellaneous-order-plot-series.ipynb) -- [show-counts-and-percentages-for-bar-plots](/plotnine-examples/plotnine_examples/tutorials/miscellaneous-show-counts-and-percentages-for-bar-plots.ipynb) -- [show-counts-on-a-stacked-bar-plot](/plotnine-examples/plotnine_examples/tutorials/miscellaneous-show-counts-on-a-stacked-bar-plot.ipynb) -- [using-letter-as-shapes](/plotnine-examples/plotnine_examples/tutorials/miscellaneous-using-letter-as-shapes.ipynb) -- [using-notebook-widgets](/plotnine-examples/plotnine_examples/tutorials/miscellaneous-using-notebook-widgets.ipynb) +- [a-pyqt5-application](/plotnine_examples/tutorials/miscellaneous-a-pyqt5-application.ipynb) +- [altering-colors](/plotnine_examples/tutorials/miscellaneous-altering-colors.ipynb) +- [automatic-grouping-insufficient](/plotnine_examples/tutorials/miscellaneous-automatic-grouping-insufficient.ipynb) +- [manipulating-date-breaks-and-date-labels](/plotnine_examples/tutorials/miscellaneous-manipulating-date-breaks-and-date-labels.ipynb) +- [order-plot-series](/plotnine_examples/tutorials/miscellaneous-order-plot-series.ipynb) +- [show-counts-and-percentages-for-bar-plots](/plotnine_examples/tutorials/miscellaneous-show-counts-and-percentages-for-bar-plots.ipynb) +- [show-counts-on-a-stacked-bar-plot](/plotnine_examples/tutorials/miscellaneous-show-counts-on-a-stacked-bar-plot.ipynb) +- [using-letter-as-shapes](/plotnine_examples/tutorials/miscellaneous-using-letter-as-shapes.ipynb) +- [using-notebook-widgets](/plotnine_examples/tutorials/miscellaneous-using-notebook-widgets.ipynb)