diff --git a/ci/requirements/doc.yml b/ci/requirements/doc.yml index d8351a41be9..0559f393bd0 100644 --- a/ci/requirements/doc.yml +++ b/ci/requirements/doc.yml @@ -4,49 +4,50 @@ channels: - conda-forge - nodefaults dependencies: - - python=3.12 + - python - bottleneck - cartopy - cfgrib - kerchunk - - dask-core>=2022.1 - - hypothesis>=6.75.8 - - h5netcdf>=0.13 + - dask-core + - hypothesis + - h5netcdf - ipykernel - ipywidgets # silence nbsphinx warning - ipython - - iris>=2.3 + - iris - jupyter_client + - jupyter_sphinx - matplotlib-base - nbsphinx - ncdata - - netcdf4>=1.5 + - netcdf4 - numba - numpy>=2 - - packaging>=23.2 - - pandas>=1.4,!=2.1.0 + - packaging + - pandas - pooch - pip - pre-commit - pyarrow + - pydata-sphinx-theme - pyproj - rich # for Zarr tree() - - scipy!=1.10.0 + - scipy - seaborn - setuptools - sparse - sphinx-autosummary-accessors - - sphinx-book-theme<=1.0.1 - sphinx-copybutton - sphinx-design - sphinx-inline-tabs - - sphinx>=5.0,<7.0 # https://github.com/executablebooks/sphinx-book-theme/issues/749 + - sphinx>=6,<8 + - sphinxcontrib-mermaid - sphinxcontrib-srclinks - sphinx-remove-toctrees - sphinxext-opengraph - sphinxext-rediraffe - - zarr>=2.10 + - zarr - pip: - - sphinxcontrib-mermaid # relative to this file. Needs to be editable to be accepted. - -e ../.. diff --git a/doc/_static/style.css b/doc/_static/style.css index 3419f89dcfc..0a19cffae00 100644 --- a/doc/_static/style.css +++ b/doc/_static/style.css @@ -1,273 +1,46 @@ -table.colwidths-given { - table-layout: fixed; - width: 100%; -} -table.docutils td { - white-space: unset; - word-wrap: break-word; -} - -.bd-header-announcement { - background-color: var(--pst-color-info-bg); -} - -/* Reduce left and right margins */ +/* Override some aspects of the pydata-sphinx-theme */ -.container, -.container-lg, -.container-md, -.container-sm, -.container-xl { - max-width: 1350px !important; -} - -/* Copied from -https://github.com/bokeh/bokeh/blob/branch-2.4/sphinx/source/bokeh/static/custom.css +/* Xarray Branding Guide: +Primary Color palette (Hex): #17afb4 #e28126 #59c7d6 #0e4666 #4a4a4a +Secondary Color Palette (Hex): #f58154 #e7b72d #b3dfe5 #8e8d99 #767985 +Primary Typeface: Acumin Variable Concept - Semicondensed Medium */ -:root { - /* Logo image height + all the paddings/margins make the navbar height. */ - --navbar-height: calc(30px + 0.3125rem * 2 + 0.5rem * 2); -} - -.bd-search { - position: relative; - padding-bottom: 20px; -} - -@media (min-width: 768px) { - .search-front-page { - width: 50%; - } -} - -/* minimal copy paste from bootstrap docs css to get sidebars working */ - -.bd-toc { - -ms-flex-order: 2; - order: 2; - padding-top: 1.5rem; - padding-bottom: 1.5rem; - /* font-size: 0.875rem; */ - /* add scrolling sidebar */ - height: calc(100vh - 2rem); - overflow-y: auto; -} - -@supports ((position: -webkit-sticky) or (position: sticky)) { - .bd-toc { - position: -webkit-sticky; - position: sticky; - top: 4rem; - height: calc(100vh - 4rem); - overflow-y: auto; - } -} - -.section-nav { - padding-left: 0; - border-left: 1px solid #eee; - border-bottom: none; -} - -.section-nav ul { - padding-left: 1rem; -} - -.toc-entry { - display: block; -} - -.toc-entry a { - display: block; - padding: 0.125rem 1.5rem; - color: #77757a; -} - -.toc-entry a:hover { - color: rgba(0, 0, 0, 0.85); - text-decoration: none; -} - -.bd-sidebar { - -ms-flex-order: 0; - order: 0; - border-bottom: 1px solid rgba(0, 0, 0, 0.1); -} - -@media (min-width: 768px) { - .bd-sidebar { - border-right: 1px solid rgba(0, 0, 0, 0.1); - } - @supports ((position: -webkit-sticky) or (position: sticky)) { - .bd-sidebar { - position: -webkit-sticky; - position: sticky; - top: var(--navbar-height); - z-index: 1000; - height: calc(100vh - var(--navbar-height)); - } - } -} - -@media (min-width: 1200px) { - .bd-sidebar { - -ms-flex: 0 1 320px; - flex: 0 1 320px; - } -} - -.bd-links { - padding-top: 1rem; - padding-bottom: 1rem; - margin-right: -15px; - margin-left: -15px; -} - -@media (min-width: 768px) { - @supports ((position: -webkit-sticky) or (position: sticky)) { - .bd-links { - max-height: calc(100vh - 9rem); - overflow-y: auto; - } - } -} - -@media (min-width: 768px) { - .bd-links { - display: block !important; - } -} - -.bd-sidenav { - display: none; -} - -.bd-toc-link { - display: block; - padding: 0.25rem 1.5rem; - font-weight: 400; - color: rgba(0, 0, 0, 0.65); +/* Increase Xarray logo size in upper left corner */ +.navbar-brand img { + height: 75px; } - -.bd-toc-link:hover { - color: rgba(0, 0, 0, 0.85); - text-decoration: none; +.navbar-brand { + height: 75px; } -.bd-toc-item.active { - margin-bottom: 1rem; +/* Adjust index page overview cards, borrowed from Pandas & Numpy */ +/* Override SVG icon color */ +html[data-theme="dark"] .sd-card img[src*=".svg"] { + filter: invert(0.82) brightness(0.8) contrast(1.2); } - -.bd-toc-item.active:not(:first-child) { - margin-top: 1rem; +/* https://github.com/executablebooks/sphinx-design/blob/main/style/_cards.scss */ +/* More space around image */ +.intro-card { + padding: 30px 1px 1px 1px; } - -.bd-toc-item.active > .bd-toc-link { - color: rgba(0, 0, 0, 0.85); +/* More prominent card borders */ +.intro-card .sd-card { + border: 2px solid var(--pst-color-border); + overflow: hidden; } - -.bd-toc-item.active > .bd-toc-link:hover { - background-color: transparent; +/* Shrink SVG icons */ +.intro-card .sd-card-img-top { + margin: 1px; + height: 100px; + background-color: transparent !important; } - -.bd-toc-item.active > .bd-sidenav { - display: block; +/* Color titles like links */ +.intro-card .sd-card-title { + color: var(--pst-color-primary); + font-size: var(--pst-font-size-h5); } - -.bd-sidebar .nav > li > a { - display: block; - padding: 0.25rem 1.5rem; - font-size: 90%; -} - -.bd-sidebar .nav > li > a:hover { - text-decoration: none; - background-color: transparent; -} - -.bd-sidebar .nav > .active > a, -.bd-sidebar .nav > .active:hover > a { - font-weight: 400; - /* adjusted from original - color: rgba(0, 0, 0, 0.85); - background-color: transparent; */ -} - -.bd-sidebar .nav > li > ul { - list-style: none; - padding: 0.25rem 1.5rem; -} - -.bd-sidebar .nav > li > ul > li > a { - display: block; - padding: 0.25rem 1.5rem; - font-size: 90%; -} - -.bd-sidebar .nav > li > ul > .active > a, -.bd-sidebar .nav > li > ul > .active:hover > a { - font-weight: 400; -} - -dt:target { - background-color: initial; -} - -/* Offsetting anchored elements within the main content to adjust for fixed header - https://github.com/pandas-dev/pandas-sphinx-theme/issues/6 */ -main *:target::before { - display: block; - content: ""; - height: var(--navbar-height); - margin-top: calc(-1 * var(--navbar-height)); -} - -body { - width: 100%; -} - -/* adjust toc font sizes to improve overview */ -.toc-h2 { - font-size: 0.85rem; -} - -.toc-h3 { - font-size: 0.75rem; -} - -.toc-h4 { - font-size: 0.65rem; -} - -.toc-entry > .nav-link.active { - font-weight: 400; - color: #542437; - background-color: transparent; - border-left: 2px solid #563d7c; -} - -.nav-link:hover { - border-style: none; -} - -/* Collapsing of the TOC sidebar while scrolling */ - -/* Nav: hide second level (shown on .active) */ -.bd-toc .nav .nav { - display: none; -} - -.bd-toc .nav > .active > ul { - display: block; -} - -/* Main index page overview cards */ - -.sd-card-img-top { - width: 33% !important; - display: block; - margin-left: auto; - margin-right: auto; - margin-top: 10px; +/* Don't have 'raised' color background for card interiors in dark mode */ +.bd-content .sd-card .sd-card-body { + background-color: unset !important; } diff --git a/doc/api.rst b/doc/api.rst index 966d7b82ddc..27f5d05d41c 100644 --- a/doc/api.rst +++ b/doc/api.rst @@ -1655,9 +1655,9 @@ Exceptions raised when manipulating trees. .. autosummary:: :toctree: generated/ - xarray.TreeIsomorphismError - xarray.InvalidTreeError - xarray.NotFoundInTreeError + TreeIsomorphismError + InvalidTreeError + NotFoundInTreeError Advanced API ============ diff --git a/doc/conf.py b/doc/conf.py index d4328dbf1b0..7a5ec4b0a5e 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -1,17 +1,3 @@ -# -# xarray documentation build configuration file, created by -# sphinx-quickstart on Thu Feb 6 18:57:54 2014. -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - - import datetime import inspect import os @@ -58,9 +44,6 @@ ] ) -nbsphinx_allow_errors = False -nbsphinx_requirejs_path = "" - # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. @@ -80,6 +63,7 @@ "sphinx.ext.napoleon", "IPython.sphinxext.ipython_directive", "IPython.sphinxext.ipython_console_highlighting", + "jupyter_sphinx", "nbsphinx", "sphinx_autosummary_accessors", "sphinx.ext.linkcode", @@ -98,14 +82,25 @@ "discussion": ("https://github.com/pydata/xarray/discussions/%s", "D%s"), } -# sphinx-copybutton configurations +# sphinx-copybutton configuration copybutton_prompt_text = r">>> |\.\.\. |\$ |In \[\d*\]: | {2,5}\.{3,}: | {5,8}: " copybutton_prompt_is_regexp = True -# nbsphinx configurations - +# NBSphinx configuration nbsphinx_timeout = 600 nbsphinx_execute = "always" +nbsphinx_allow_errors = False +nbsphinx_requirejs_path = "" +# png2x/retina rendering of figues in docs would also need to modify custom.css: +# https://github.com/spatialaudio/nbsphinx/issues/464#issuecomment-652729126 +# .rst-content .image-reference img { +# max-width: unset; +# width: 100% !important; +# height: auto !important; +# } +# nbsphinx_execute_arguments = [ +# "--InlineBackend.figure_formats=['png2x']", +# ] nbsphinx_prolog = """ {% set docname = env.doc2path(env.docname, base=None) %} @@ -115,11 +110,11 @@ :target: https://mybinder.org/v2/gh/pydata/xarray/main?urlpath=lab/tree/doc/{{ docname }} """ +# AutoDoc configuration autosummary_generate = True autodoc_typehints = "none" -# Napoleon configurations - +# Napoleon configuration napoleon_google_docstring = False napoleon_numpy_docstring = True napoleon_use_param = False @@ -193,14 +188,12 @@ # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates", sphinx_autosummary_accessors.templates_path] -# The suffix of source filenames. -# source_suffix = ".rst" - - # The master toctree document. master_doc = "index" remove_from_toctrees = ["generated/*"] +# The language for content autogenerated by Sphinx. +language = "en" # General information about the project. project = "xarray" @@ -229,7 +222,7 @@ # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. -html_theme = "sphinx_book_theme" +html_theme = "pydata_sphinx_theme" html_title = "" html_context = { @@ -239,29 +232,37 @@ "doc_path": "doc", } -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = dict( - # analytics_id='' this is configured in rtfd.io - # canonical_url="", - repository_url="https://github.com/pydata/xarray", - repository_branch="main", - navigation_with_keys=False, # pydata/pydata-sphinx-theme#1492 - navigation_depth=4, - path_to_docs="doc", - use_edit_page_button=True, - use_repository_button=True, - use_issues_button=True, - home_page_in_toc=False, - extra_footer="""<p>Xarray is a fiscally sponsored project of <a href="https://numfocus.org">NumFOCUS</a>, - a nonprofit dedicated to supporting the open-source scientific computing community.<br> - Theme by the <a href="https://ebp.jupyterbook.org">Executable Book Project</a></p>""", - twitter_url="https://twitter.com/xarray_dev", - icon_links=[], # workaround for pydata/pydata-sphinx-theme#1220 - # announcement="<a href='https://forms.gle/KEq7WviCdz9xTaJX6'>Xarray's 2024 User Survey is live now. Please take ~5 minutes to fill it out and help us improve Xarray.</a>", -) - +# https://pydata-sphinx-theme.readthedocs.io/en/stable/user_guide/layout.html#references +html_theme_options = { + #"announcement":"🍾 <a href='https://github.com/pydata/xarray/discussions/8462'>Xarray is now 10 years old!</a> 🎉", + "logo": {"image_dark": "https://docs.xarray.dev/en/stable/_static/logos/Xarray_Logo_FullColor_InverseRGB_Final.svg"}, + "github_url":"https://github.com/pydata/xarray", + "show_version_warning_banner":True, + "use_edit_page_button":True, + "header_links_before_dropdown": 8, + "navbar_align": "left", + "footer_center":["last-updated"], + # Instead of adding these to the header bar they are linked in 'getting help' and 'contributing' + # "icon_links": [ + # { + # "name": "Discord", + # "url": "https://discord.com/invite/wEKPCt4PDu", + # "icon": "fa-brands fa-discord", + # }, + # { + # "name": "X", + # "url": "https://x.com/xarray_dev", + # "icon": "fa-brands fa-x-twitter", + # }, + # { + # "name": "Bluesky", + # "url": "https://bsky.app/profile/xarray.bsky.social", + # "icon": "fa-brands fa-bluesky", + # }, + # ] +} +# pydata_sphinx_theme use_edit_page_button with github link seems better +html_show_sourcelink = False # The name of an image file (relative to this directory) to place at the top # of the sidebar. @@ -289,7 +290,6 @@ ] # Redirects for pages that were moved to new locations - rediraffe_redirects = { "terminology.rst": "user-guide/terminology.rst", "data-structures.rst": "user-guide/data-structures.rst", @@ -306,23 +306,13 @@ "dask.rst": "user-guide/dask.rst", "plotting.rst": "user-guide/plotting.rst", "duckarrays.rst": "user-guide/duckarrays.rst", - "related-projects.rst": "ecosystem.rst", - "faq.rst": "getting-started-guide/faq.rst", + "related-projects.rst": "user-guide/ecosystem.rst", + "faq.rst": "get-help/faq.rst", "why-xarray.rst": "getting-started-guide/why-xarray.rst", "installing.rst": "getting-started-guide/installing.rst", "quick-overview.rst": "getting-started-guide/quick-overview.rst", } -# Sometimes the savefig directory doesn't exist and needs to be created -# https://github.com/ipython/ipython/issues/8733 -# becomes obsolete when we can pin ipython>=5.2; see ci/requirements/doc.yml -ipython_savefig_dir = os.path.join( - os.path.dirname(os.path.abspath(__file__)), "_build", "html", "_static" -) -if not os.path.exists(ipython_savefig_dir): - os.makedirs(ipython_savefig_dir) - - # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = today_fmt @@ -350,7 +340,6 @@ "zarr": ("https://zarr.readthedocs.io/en/stable/", None), } - # based on numpy doc/source/conf.py def linkcode_resolve(domain, info): """ diff --git a/doc/contributing.rst b/doc/contribute/contributing.rst similarity index 99% rename from doc/contributing.rst rename to doc/contribute/contributing.rst index 2a91759744b..10c9dbb4baa 100644 --- a/doc/contributing.rst +++ b/doc/contribute/contributing.rst @@ -609,7 +609,7 @@ A pull-request will be considered for merging when you have an all 'green' build tests are failing, then you will get a red 'X', where you can click through to see the individual failed tests. This is an example of a green build. -.. image:: _static/ci.png +.. image:: ../_static/ci.png .. note:: @@ -1013,7 +1013,7 @@ If you have made updates to the documentation, you can now see a preview of the the ``docs/readthedocs.org`` check near the bottom of the list of checks that run automatically when submitting a PR, then clicking on the "View Docs" button on the right (not the big green button, the small black one further down). -.. image:: _static/view-docs.png +.. image:: ../_static/view-docs.png If you need to make more changes, you can make them in diff --git a/doc/developers-meeting.rst b/doc/contribute/developers-meeting.rst similarity index 98% rename from doc/developers-meeting.rst rename to doc/contribute/developers-meeting.rst index edf8af72059..8297c54e8ce 100644 --- a/doc/developers-meeting.rst +++ b/doc/contribute/developers-meeting.rst @@ -1,3 +1,5 @@ +.. _developers-meeting: + Developers meeting ------------------ diff --git a/doc/contribute/index.rst b/doc/contribute/index.rst new file mode 100644 index 00000000000..c4461d38039 --- /dev/null +++ b/doc/contribute/index.rst @@ -0,0 +1,19 @@ +################## +Contributors Guide +################## + +We welcome your skills and enthusiasm at the Xarray project! There are numerous opportunities to +contribute beyond just writing code. +All contributions, including bug reports, bug fixes, documentation improvements, enhancement suggestions, +and other ideas are welcome. + +.. toctree:: + :maxdepth: 2 + :hidden: + + contributing + ../internals/index + ../roadmap + ../whats-new + developers-meeting + Team <https://xarray.dev/team> diff --git a/doc/examples/ERA5-GRIB-example.ipynb b/doc/examples/ERA5-GRIB-example.ipynb index 5d09f1a7431..d21c8b9ca89 100644 --- a/doc/examples/ERA5-GRIB-example.ipynb +++ b/doc/examples/ERA5-GRIB-example.ipynb @@ -21,7 +21,8 @@ "outputs": [], "source": [ "import xarray as xr\n", - "import matplotlib.pyplot as plt" + "import matplotlib.pyplot as plt\n", + "%matplotlib inline" ] }, { diff --git a/doc/examples/monthly_means_output.png b/doc/examples/monthly_means_output.png deleted file mode 100644 index a2b3afb916e..00000000000 Binary files a/doc/examples/monthly_means_output.png and /dev/null differ diff --git a/doc/examples/weather-data.ipynb b/doc/examples/weather-data.ipynb index f582453aacf..a3682dc7b6d 100644 --- a/doc/examples/weather-data.ipynb +++ b/doc/examples/weather-data.ipynb @@ -10,6 +10,20 @@ "xarray and other recommended Python libraries:" ] }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import seaborn as sns\n", + "\n", + "import xarray as xr\n", + "%matplotlib inline" + ] + }, { "cell_type": "code", "execution_count": null, @@ -21,12 +35,6 @@ }, "outputs": [], "source": [ - "import numpy as np\n", - "import pandas as pd\n", - "import seaborn as sns\n", - "\n", - "import xarray as xr\n", - "\n", "np.random.seed(123)\n", "\n", "xr.set_options(display_style=\"html\")\n", diff --git a/doc/gallery.rst b/doc/gallery.rst index 61ec45c7bda..9e0cb22da6b 100644 --- a/doc/gallery.rst +++ b/doc/gallery.rst @@ -3,7 +3,7 @@ Gallery Here's a list of examples on how to use xarray. We will be adding more examples soon. Contributions are highly welcomed and appreciated. So, if you are interested in contributing, please consult the -:doc:`contributing` guide. +:ref:`contributing` guide. diff --git a/doc/getting-started-guide/faq.rst b/doc/get-help/faq.rst similarity index 100% rename from doc/getting-started-guide/faq.rst rename to doc/get-help/faq.rst diff --git a/doc/help-diagram.rst b/doc/get-help/help-diagram.rst similarity index 84% rename from doc/help-diagram.rst rename to doc/get-help/help-diagram.rst index a42a2f0936a..9ee07426e95 100644 --- a/doc/help-diagram.rst +++ b/doc/get-help/help-diagram.rst @@ -4,7 +4,12 @@ Getting Help Navigating the wealth of resources available for Xarray can be overwhelming. We've created this flow chart to help guide you towards the best way to get help, depending on what you're working towards. The links to each resource are provided below the diagram. -Regardless of how you interact with us, we're always thrilled to hear from you! + +Also be sure to check out our "FAQ" and "How do I..." pages in this section for solutions to common questions. + +A major strength of Xarray is in the user community. Sometimes you might not have a concrete question by would simply like to connect with other Xarray users. We have a few + +We look forward to hearing from you! .. mermaid:: :alt: Flowchart illustrating the different ways to access help using or contributing to Xarray. @@ -62,14 +67,24 @@ Regardless of how you interact with us, we're always thrilled to hear from you! linkStyle default font-size:20pt,color:#206C89 - +Flowchart links +--------------- - `Xarray Tutorials <https://tutorial.xarray.dev/>`__ -- `Xarray Docs <https://docs.xarray.dev/en/stable/>`__ +- `Xarray Docs <https://docs.xarray.dev>`__ - `Google/Stack Exchange <https://stackoverflow.com/questions/tagged/python-xarray>`__ - `Xarray Discussions <https://github.com/pydata/xarray/discussions>`__ - `Xarray Discord <https://discord.com/invite/wEKPCt4PDu>`__ - `Xarray Office Hours <https://github.com/pydata/xarray/discussions/categories/office-hours>`__ - `Pangeo Discourse <https://discourse.pangeo.io/>`__ - `Xarray Issues <https://github.com/pydata/xarray/issues>`__ -- `Xarray Contributors Guide <https://docs.xarray.dev/en/stable/contributing.html>`__ -- `Developer's Meeting <https://docs.xarray.dev/en/stable/developers-meeting.html>`__ +- :ref:`contributing` +- :ref:`developers-meeting` + + +.. toctree:: + :maxdepth: 1 + :hidden: + + faq + howdoi + socials diff --git a/doc/howdoi.rst b/doc/get-help/howdoi.rst similarity index 100% rename from doc/howdoi.rst rename to doc/get-help/howdoi.rst diff --git a/doc/get-help/socials.rst b/doc/get-help/socials.rst new file mode 100644 index 00000000000..b63b3529a73 --- /dev/null +++ b/doc/get-help/socials.rst @@ -0,0 +1,10 @@ +.. _socials: + +Social Media +============ + +Xarray is active on several social media platforms. We use these platforms to share updates and connect with the user community. + +- `Discord <https://discord.com/invite/wEKPCt4PDu>`__ +- `Bluesky <https://bsky.app/profile/xarray.bsky.social>`__ +- `Twitter(X) <https://x.com/xarray_dev>`__ diff --git a/doc/getting-started-guide/index.rst b/doc/getting-started-guide/index.rst index 20fd49fb2c4..cf092147ff7 100644 --- a/doc/getting-started-guide/index.rst +++ b/doc/getting-started-guide/index.rst @@ -2,14 +2,13 @@ Getting Started ################ -The getting started guide aims to get you using xarray productively as quickly as possible. -It is designed as an entry point for new users, and it provided an introduction to xarray's main concepts. +The getting started guide aims to get you using Xarray productively as quickly as possible. +It is designed as an entry point for new users, and it provided an introduction to Xarray's main concepts. .. toctree:: :maxdepth: 2 - :hidden: why-xarray installing quick-overview - faq + tutorials-and-videos diff --git a/doc/getting-started-guide/quick-overview.rst b/doc/getting-started-guide/quick-overview.rst index d60156caa5b..422b5217ab1 100644 --- a/doc/getting-started-guide/quick-overview.rst +++ b/doc/getting-started-guide/quick-overview.rst @@ -8,7 +8,7 @@ documentation. To begin, import numpy, pandas and xarray using their customary abbreviations: -.. ipython:: python +.. jupyter-execute:: import numpy as np import pandas as pd @@ -20,20 +20,20 @@ Create a DataArray You can make a DataArray from scratch by supplying data in the form of a numpy array or list, with optional *dimensions* and *coordinates*: -.. ipython:: python +.. jupyter-execute:: data = xr.DataArray(np.random.randn(2, 3), dims=("x", "y"), coords={"x": [10, 20]}) data In this case, we have generated a 2D array, assigned the names *x* and *y* to the two dimensions respectively and associated two *coordinate labels* '10' and '20' with the two locations along the x dimension. If you supply a pandas :py:class:`~pandas.Series` or :py:class:`~pandas.DataFrame`, metadata is copied directly: -.. ipython:: python +.. jupyter-execute:: xr.DataArray(pd.Series(range(3), index=list("abc"), name="foo")) Here are the key properties for a ``DataArray``: -.. ipython:: python +.. jupyter-execute:: # like in pandas, values is a numpy array that you can modify in-place data.values @@ -48,7 +48,7 @@ Indexing Xarray supports four kinds of indexing. Since we have assigned coordinate labels to the x dimension we can use label-based indexing along that dimension just like pandas. The four examples below all yield the same result (the value at ``x=10``) but at varying levels of convenience and intuitiveness. -.. ipython:: python +.. jupyter-execute:: # positional and by integer label, like numpy data[0, :] @@ -71,7 +71,7 @@ Attributes While you're setting up your DataArray, it's often a good idea to set metadata attributes. A useful choice is to set ``data.attrs['long_name']`` and ``data.attrs['units']`` since xarray will use these, if present, to automatically label your plots. These special names were chosen following the `NetCDF Climate and Forecast (CF) Metadata Conventions <https://cfconventions.org/cf-conventions/cf-conventions.html>`_. ``attrs`` is just a Python dictionary, so you can assign anything you wish. -.. ipython:: python +.. jupyter-execute:: data.attrs["long_name"] = "random velocity" data.attrs["units"] = "metres/sec" @@ -87,7 +87,7 @@ Computation Data arrays work very similarly to numpy ndarrays: -.. ipython:: python +.. jupyter-execute:: data + 10 np.sin(data) @@ -98,14 +98,14 @@ Data arrays work very similarly to numpy ndarrays: However, aggregation operations can use dimension names instead of axis numbers: -.. ipython:: python +.. jupyter-execute:: data.mean(dim="x") Arithmetic operations broadcast based on dimension name. This means you don't need to insert dummy dimensions for alignment: -.. ipython:: python +.. jupyter-execute:: a = xr.DataArray(np.random.randn(3), [data.coords["y"]]) b = xr.DataArray(np.random.randn(4), dims="z") @@ -118,13 +118,13 @@ need to insert dummy dimensions for alignment: It also means that in most cases you do not need to worry about the order of dimensions: -.. ipython:: python +.. jupyter-execute:: data - data.T Operations also align based on index labels: -.. ipython:: python +.. jupyter-execute:: data[:-1] - data[:1] @@ -135,7 +135,7 @@ GroupBy Xarray supports grouped operations using a very similar API to pandas (see :ref:`groupby`): -.. ipython:: python +.. jupyter-execute:: labels = xr.DataArray(["E", "F", "E"], [data.coords["y"]], name="labels") labels @@ -147,9 +147,8 @@ Plotting Visualizing your datasets is quick and convenient: -.. ipython:: python +.. jupyter-execute:: - @savefig plotting_quick_overview.png data.plot() Note the automatic labeling with names and units. Our effort in adding metadata attributes has paid off! Many aspects of these figures are customizable: see :ref:`plotting`. @@ -159,7 +158,7 @@ pandas Xarray objects can be easily converted to and from pandas objects using the :py:meth:`~xarray.DataArray.to_series`, :py:meth:`~xarray.DataArray.to_dataframe` and :py:meth:`~pandas.DataFrame.to_xarray` methods: -.. ipython:: python +.. jupyter-execute:: series = data.to_series() series @@ -174,7 +173,7 @@ Datasets objects. You can think of it as a multi-dimensional generalization of the :py:class:`pandas.DataFrame`: -.. ipython:: python +.. jupyter-execute:: ds = xr.Dataset(dict(foo=data, bar=("x", [1, 2]), baz=np.pi)) ds @@ -182,7 +181,7 @@ objects. You can think of it as a multi-dimensional generalization of the This creates a dataset with three DataArrays named ``foo``, ``bar`` and ``baz``. Use dictionary or dot indexing to pull out ``Dataset`` variables as ``DataArray`` objects but note that assignment only works with dictionary indexing: -.. ipython:: python +.. jupyter-execute:: ds["foo"] ds.foo @@ -192,7 +191,7 @@ When creating ``ds``, we specified that ``foo`` is identical to ``data`` created For example, when creating ``ds`` xarray automatically *aligns* ``bar`` with ``DataArray`` ``foo``, i.e., they share the same coordinate system so that ``ds.bar['x'] == ds.foo['x'] == ds['x']``. Consequently, the following works without explicitly specifying the coordinate ``x`` when creating ``ds['bar']``: -.. ipython:: python +.. jupyter-execute:: ds.bar.sel(x=10) @@ -212,14 +211,14 @@ model looks very similar to a netCDF file (which, in fact, inspired it). You can directly read and write xarray objects to disk using :py:meth:`~xarray.Dataset.to_netcdf`, :py:func:`~xarray.open_dataset` and :py:func:`~xarray.open_dataarray`: -.. ipython:: python +.. jupyter-execute:: ds.to_netcdf("example.nc") reopened = xr.open_dataset("example.nc") reopened -.. ipython:: python - :suppress: +.. jupyter-execute:: + :hide-code: import os @@ -239,7 +238,7 @@ DataTrees Let's first make some example xarray datasets: -.. ipython:: python +.. jupyter-execute:: import numpy as np import xarray as xr @@ -259,7 +258,7 @@ Let's first make some example xarray datasets: Now we'll put these datasets into a hierarchical DataTree: -.. ipython:: python +.. jupyter-execute:: dt = xr.DataTree.from_dict( {"simulation/coarse": ds, "simulation/fine": ds2, "/": ds3} @@ -290,26 +289,26 @@ addition of requiring parent-descendent coordinate agreement. We created the subgroups using a filesystem-like syntax, and accessing groups works the same way. We can access individual DataArrays in a similar fashion. -.. ipython:: python +.. jupyter-execute:: dt["simulation/coarse/foo"] We can also view the data in a particular group as a read-only :py:class:`~xarray.Datatree.DatasetView` using :py:attr:`xarray.Datatree.dataset`: -.. ipython:: python +.. jupyter-execute:: dt["simulation/coarse"].dataset We can get a copy of the :py:class:`~xarray.Dataset` including the inherited coordinates by calling the :py:class:`~xarray.datatree.to_dataset` method: -.. ipython:: python +.. jupyter-execute:: ds_inherited = dt["simulation/coarse"].to_dataset() ds_inherited And you can get a copy of just the node local values of :py:class:`~xarray.Dataset` by setting the ``inherit`` keyword to ``False``: -.. ipython:: python +.. jupyter-execute:: ds_node_local = dt["simulation/coarse"].to_dataset(inherit=False) ds_node_local @@ -322,7 +321,7 @@ And you can get a copy of just the node local values of :py:class:`~xarray.Datas .. Operations map over subtrees, so we can take a mean over the ``x`` dimension of both the ``fine`` and ``coarse`` groups just by: -.. .. ipython:: python +.. .. jupyter-execute:: .. avg = dt["simulation"].mean(dim="x") .. avg diff --git a/doc/tutorials-and-videos.rst b/doc/getting-started-guide/tutorials-and-videos.rst similarity index 77% rename from doc/tutorials-and-videos.rst rename to doc/getting-started-guide/tutorials-and-videos.rst index 7a9e524340b..e8e2bf56db4 100644 --- a/doc/tutorials-and-videos.rst +++ b/doc/getting-started-guide/tutorials-and-videos.rst @@ -2,6 +2,9 @@ Tutorials and Videos ==================== +There are an abundance of tutorials and videos available for learning how to use *xarray*. +Often, these tutorials are taught to workshop attendees at conferences or other events. +We highlight a number of these resources below, but this is by no means an exhaustive list! Tutorials ---------- @@ -11,11 +14,10 @@ Tutorials - `Nicolas Fauchereau's 2015 tutorial`_ on xarray for netCDF users. - Videos ------- -.. include:: videos-gallery.txt +.. include:: ../videos-gallery.txt Books, Chapters and Articles diff --git a/doc/index.rst b/doc/index.rst index 4a5fe4ee080..455dd3c5e80 100644 --- a/doc/index.rst +++ b/doc/index.rst @@ -1,3 +1,5 @@ +:html_theme.sidebar_secondary.remove: true + .. module:: xarray Xarray documentation @@ -6,86 +8,67 @@ Xarray documentation Xarray makes working with labelled multi-dimensional arrays in Python simple, efficient, and fun! +**Version**: |version| - :ref:`whats-new` + **Useful links**: `Home <https://xarray.dev>`__ | `Code Repository <https://github.com/pydata/xarray>`__ | `Issues <https://github.com/pydata/xarray/issues>`__ | `Discussions <https://github.com/pydata/xarray/discussions>`__ | `Releases <https://github.com/pydata/xarray/releases>`__ | +`Tutorial <https://tutorial.xarray.dev>`__ | `Stack Overflow <https://stackoverflow.com/questions/tagged/python-xarray>`__ | -`Mailing List <https://groups.google.com/g/xarray>`__ | `Blog <https://xarray.dev/blog>`__ | -`Tutorials <https://tutorial.xarray.dev/>`__ - .. grid:: 1 1 2 2 :gutter: 2 - .. grid-item-card:: Getting started + .. grid-item-card:: Get started! :img-top: _static/index_getting_started.svg + :class-card: intro-card :link: getting-started-guide/index :link-type: doc - New to *xarray*? Check out the getting started guides. They contain an - introduction to *Xarray's* main concepts and links to additional tutorials. + *New to Xarray?* + Start here with our installation instructions and a brief overview of Xarray. .. grid-item-card:: User guide :img-top: _static/index_user_guide.svg + :class-card: intro-card :link: user-guide/index :link-type: doc - The user guide provides in-depth information on the - key concepts of Xarray with useful background information and explanation. + *Ready to deepen your understanding of Xarray?* + Visit the user guide for detailed explanations of the data model, common computational patterns, and more. .. grid-item-card:: API reference :img-top: _static/index_api.svg + :class-card: intro-card :link: api :link-type: doc - The reference guide contains a detailed description of the Xarray API. - The reference describes how the methods work and which parameters can - be used. It assumes that you have an understanding of the key concepts. + *Need to learn more about a specific Xarray function?* + Go here to review the documentation of all public functions and classes in Xarray. - .. grid-item-card:: Developer guide + .. grid-item-card:: Contribute :img-top: _static/index_contribute.svg - :link: contributing + :class-card: intro-card + :link: contribute/contributing :link-type: doc - Saw a typo in the documentation? Want to improve existing functionalities? - The contributing guidelines will guide you through the process of improving - Xarray. + *Saw a typo in the documentation? Want to improve existing functionalities?* + Please review our guide on improving Xarray. .. toctree:: :maxdepth: 2 :hidden: :caption: For users - Getting Started <getting-started-guide/index> + Get Started <getting-started-guide/index> User Guide <user-guide/index> + Tutorial <https://tutorial.xarray.dev> Gallery <gallery> - Tutorials & Videos <tutorials-and-videos> API Reference <api> - How do I ... <howdoi> - Getting Help <help-diagram> - Ecosystem <ecosystem> - -.. toctree:: - :maxdepth: 2 - :hidden: - :caption: For developers/contributors - - Contributing Guide <contributing> - Xarray Internals <internals/index> - Development Roadmap <roadmap> - Team <https://xarray.dev/team> - Developers Meeting <developers-meeting> - What’s New <whats-new> - GitHub repository <https://github.com/pydata/xarray> - -.. toctree:: - :maxdepth: 1 - :hidden: - :caption: Community - - GitHub discussions <https://github.com/pydata/xarray/discussions> - StackOverflow <https://stackoverflow.com/questions/tagged/python-xarray> + Get Help <get-help/help-diagram> + Contribute <contribute/index> + Release Notes <whats-new> diff --git a/doc/ecosystem.rst b/doc/user-guide/ecosystem.rst similarity index 100% rename from doc/ecosystem.rst rename to doc/user-guide/ecosystem.rst diff --git a/doc/user-guide/index.rst b/doc/user-guide/index.rst index d8c4964457b..940cda1c1cc 100644 --- a/doc/user-guide/index.rst +++ b/doc/user-guide/index.rst @@ -3,28 +3,62 @@ User Guide ########### In this user guide, you will find detailed descriptions and -examples that describe many common tasks that you can accomplish with xarray. +examples that describe many common tasks that you can accomplish with Xarray. .. toctree:: :maxdepth: 2 - :hidden: + :caption: Data model terminology data-structures + hierarchical-data + dask + + +.. toctree:: + :maxdepth: 2 + :caption: Core operations + indexing - interpolation + combining + reshaping computation groupby - reshaping - combining - time-series - weather-climate - pandas + interpolation + +.. toctree:: + :maxdepth: 2 + :caption: I/O + io - dask + +.. toctree:: + :maxdepth: 2 + :caption: Visualization + plotting + + +.. toctree:: + :maxdepth: 2 + :caption: Interoperatbility + + pandas + duckarrays + ecosystem + + +.. toctree:: + :maxdepth: 2 + :caption: Domain-specific workflows + + time-series + weather-climate + +.. toctree:: + :maxdepth: 2 + :caption: Options and Testing + options testing - duckarrays - hierarchical-data diff --git a/doc/whats-new.rst b/doc/whats-new.rst index 48cd69ad82d..a0b9e300a94 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -1,5 +1,7 @@ .. currentmodule:: xarray +.. _whats-new: + What's New ========== @@ -59,6 +61,8 @@ Documentation By `Mattia Almansi <https://github.com/malmans2>`_. - Fix references to point to updated pydap documentation (:pull:`10182`). By `Miguel Jimenez-Urias <https://github.com/Mikejmnez>`_. +- Switch to `pydata-sphinx-theme <https://github.com/pydata/pydata-sphinx-theme>`_ from `sphinx-book-theme <https://github.com/executablebooks/sphinx-book-theme>`_ (:pull:`8708`). + By `Scott Henderson <https://github.com/scottyhq>`_. Internal Changes ~~~~~~~~~~~~~~~~ @@ -3861,11 +3865,11 @@ Documentation - Raise a more informative error when :py:meth:`DataArray.to_dataframe` is is called on a scalar, (:issue:`4228`); By `Pieter Gijsbers <https://github.com/pgijsbers>`_. -- Fix grammar and typos in the :doc:`contributing` guide (:pull:`4545`). +- Fix grammar and typos in the :ref:`contributing` guide (:pull:`4545`). By `Sahid Velji <https://github.com/sahidvelji>`_. - Fix grammar and typos in the :doc:`user-guide/io` guide (:pull:`4553`). By `Sahid Velji <https://github.com/sahidvelji>`_. -- Update link to NumPy docstring standard in the :doc:`contributing` guide (:pull:`4558`). +- Update link to NumPy docstring standard in the :ref:`contributing` guide (:pull:`4558`). By `Sahid Velji <https://github.com/sahidvelji>`_. - Add docstrings to ``isnull`` and ``notnull``, and fix the displayed signature (:issue:`2760`, :pull:`4618`). @@ -6172,7 +6176,7 @@ Documentation - Added apply_ufunc example to :ref:`/examples/weather-data.ipynb#Toy-weather-data` (:issue:`1844`). By `Liam Brannigan <https://github.com/braaannigan>`_. - New entry ``Why don’t aggregations return Python scalars?`` in the - :doc:`getting-started-guide/faq` (:issue:`1726`). + :ref:`faq` (:issue:`1726`). By `0x0L <https://github.com/0x0L>`_. Enhancements diff --git a/xarray/plot/dataarray_plot.py b/xarray/plot/dataarray_plot.py index 4d5b6ceeae9..a4ed7eba1d0 100644 --- a/xarray/plot/dataarray_plot.py +++ b/xarray/plot/dataarray_plot.py @@ -716,115 +716,115 @@ def hist( def _plot1d(plotfunc): """Decorator for common 1d plotting logic.""" commondoc = """ - Parameters - ---------- - darray : DataArray - Must be 2 dimensional, unless creating faceted plots. - x : Hashable or None, optional - Coordinate for x axis. If None use darray.dims[1]. - y : Hashable or None, optional - Coordinate for y axis. If None use darray.dims[0]. - z : Hashable or None, optional - If specified plot 3D and use this coordinate for *z* axis. - hue : Hashable or None, optional - Dimension or coordinate for which you want multiple lines plotted. - markersize: Hashable or None, optional - scatter only. Variable by which to vary size of scattered points. - linewidth: Hashable or None, optional - Variable by which to vary linewidth. - row : Hashable, optional - If passed, make row faceted plots on this dimension name. - col : Hashable, optional - If passed, make column faceted plots on this dimension name. - col_wrap : int, optional - Use together with ``col`` to wrap faceted plots - ax : matplotlib axes object, optional - If None, uses the current axis. Not applicable when using facets. - figsize : Iterable[float] or None, optional - A tuple (width, height) of the figure in inches. - Mutually exclusive with ``size`` and ``ax``. - size : scalar, optional - If provided, create a new figure for the plot with the given size. - Height (in inches) of each plot. See also: ``aspect``. - aspect : "auto", "equal", scalar or None, optional - Aspect ratio of plot, so that ``aspect * size`` gives the width in - inches. Only used if a ``size`` is provided. - xincrease : bool or None, default: True - Should the values on the x axes be increasing from left to right? - if None, use the default for the matplotlib function. - yincrease : bool or None, default: True - Should the values on the y axes be increasing from top to bottom? - if None, use the default for the matplotlib function. - add_legend : bool or None, optional - If True use xarray metadata to add a legend. - add_colorbar : bool or None, optional - If True add a colorbar. - add_labels : bool or None, optional - If True use xarray metadata to label axes - add_title : bool or None, optional - If True use xarray metadata to add a title - subplot_kws : dict, optional - Dictionary of keyword arguments for matplotlib subplots. Only applies - to FacetGrid plotting. - xscale : {'linear', 'symlog', 'log', 'logit'} or None, optional - Specifies scaling for the x-axes. - yscale : {'linear', 'symlog', 'log', 'logit'} or None, optional - Specifies scaling for the y-axes. - xticks : ArrayLike or None, optional - Specify tick locations for x-axes. - yticks : ArrayLike or None, optional - Specify tick locations for y-axes. - xlim : tuple[float, float] or None, optional - Specify x-axes limits. - ylim : tuple[float, float] or None, optional - Specify y-axes limits. - cmap : matplotlib colormap name or colormap, optional - The mapping from data values to color space. Either a - Matplotlib colormap name or object. If not provided, this will - be either ``'viridis'`` (if the function infers a sequential - dataset) or ``'RdBu_r'`` (if the function infers a diverging - dataset). - See :doc:`Choosing Colormaps in Matplotlib <matplotlib:users/explain/colors/colormaps>` - for more information. - - If *seaborn* is installed, ``cmap`` may also be a - `seaborn color palette <https://seaborn.pydata.org/tutorial/color_palettes.html>`_. - Note: if ``cmap`` is a seaborn color palette, - ``levels`` must also be specified. - vmin : float or None, optional - Lower value to anchor the colormap, otherwise it is inferred from the - data and other keyword arguments. When a diverging dataset is inferred, - setting `vmin` or `vmax` will fix the other by symmetry around - ``center``. Setting both values prevents use of a diverging colormap. - If discrete levels are provided as an explicit list, both of these - values are ignored. - vmax : float or None, optional - Upper value to anchor the colormap, otherwise it is inferred from the - data and other keyword arguments. When a diverging dataset is inferred, - setting `vmin` or `vmax` will fix the other by symmetry around - ``center``. Setting both values prevents use of a diverging colormap. - If discrete levels are provided as an explicit list, both of these - values are ignored. - norm : matplotlib.colors.Normalize, optional - If ``norm`` has ``vmin`` or ``vmax`` specified, the corresponding - kwarg must be ``None``. - extend : {'neither', 'both', 'min', 'max'}, optional - How to draw arrows extending the colorbar beyond its limits. If not - provided, ``extend`` is inferred from ``vmin``, ``vmax`` and the data limits. - levels : int or array-like, optional - Split the colormap (``cmap``) into discrete color intervals. If an integer - is provided, "nice" levels are chosen based on the data range: this can - imply that the final number of levels is not exactly the expected one. - Setting ``vmin`` and/or ``vmax`` with ``levels=N`` is equivalent to - setting ``levels=np.linspace(vmin, vmax, N)``. - **kwargs : optional - Additional arguments to wrapped matplotlib function - - Returns - ------- - artist : - The same type of primitive artist that the wrapped matplotlib - function returns +Parameters +---------- +darray : DataArray + Must be 2 dimensional, unless creating faceted plots. +x : Hashable or None, optional + Coordinate for x axis. If None use darray.dims[1]. +y : Hashable or None, optional + Coordinate for y axis. If None use darray.dims[0]. +z : Hashable or None, optional + If specified plot 3D and use this coordinate for *z* axis. +hue : Hashable or None, optional + Dimension or coordinate for which you want multiple lines plotted. +markersize: Hashable or None, optional + scatter only. Variable by which to vary size of scattered points. +linewidth: Hashable or None, optional + Variable by which to vary linewidth. +row : Hashable, optional + If passed, make row faceted plots on this dimension name. +col : Hashable, optional + If passed, make column faceted plots on this dimension name. +col_wrap : int, optional + Use together with ``col`` to wrap faceted plots +ax : matplotlib axes object, optional + If None, uses the current axis. Not applicable when using facets. +figsize : Iterable[float] or None, optional + A tuple (width, height) of the figure in inches. + Mutually exclusive with ``size`` and ``ax``. +size : scalar, optional + If provided, create a new figure for the plot with the given size. + Height (in inches) of each plot. See also: ``aspect``. +aspect : "auto", "equal", scalar or None, optional + Aspect ratio of plot, so that ``aspect * size`` gives the width in + inches. Only used if a ``size`` is provided. +xincrease : bool or None, default: True + Should the values on the x axes be increasing from left to right? + if None, use the default for the matplotlib function. +yincrease : bool or None, default: True + Should the values on the y axes be increasing from top to bottom? + if None, use the default for the matplotlib function. +add_legend : bool or None, optional + If True use xarray metadata to add a legend. +add_colorbar : bool or None, optional + If True add a colorbar. +add_labels : bool or None, optional + If True use xarray metadata to label axes +add_title : bool or None, optional + If True use xarray metadata to add a title +subplot_kws : dict, optional + Dictionary of keyword arguments for matplotlib subplots. Only applies + to FacetGrid plotting. +xscale : {'linear', 'symlog', 'log', 'logit'} or None, optional + Specifies scaling for the x-axes. +yscale : {'linear', 'symlog', 'log', 'logit'} or None, optional + Specifies scaling for the y-axes. +xticks : ArrayLike or None, optional + Specify tick locations for x-axes. +yticks : ArrayLike or None, optional + Specify tick locations for y-axes. +xlim : tuple[float, float] or None, optional + Specify x-axes limits. +ylim : tuple[float, float] or None, optional + Specify y-axes limits. +cmap : matplotlib colormap name or colormap, optional + The mapping from data values to color space. Either a + Matplotlib colormap name or object. If not provided, this will + be either ``'viridis'`` (if the function infers a sequential + dataset) or ``'RdBu_r'`` (if the function infers a diverging + dataset). + See :doc:`Choosing Colormaps in Matplotlib <matplotlib:users/explain/colors/colormaps>` + for more information. + + If *seaborn* is installed, ``cmap`` may also be a + `seaborn color palette <https://seaborn.pydata.org/tutorial/color_palettes.html>`_. + Note: if ``cmap`` is a seaborn color palette, + ``levels`` must also be specified. +vmin : float or None, optional + Lower value to anchor the colormap, otherwise it is inferred from the + data and other keyword arguments. When a diverging dataset is inferred, + setting `vmin` or `vmax` will fix the other by symmetry around + ``center``. Setting both values prevents use of a diverging colormap. + If discrete levels are provided as an explicit list, both of these + values are ignored. +vmax : float or None, optional + Upper value to anchor the colormap, otherwise it is inferred from the + data and other keyword arguments. When a diverging dataset is inferred, + setting `vmin` or `vmax` will fix the other by symmetry around + ``center``. Setting both values prevents use of a diverging colormap. + If discrete levels are provided as an explicit list, both of these + values are ignored. +norm : matplotlib.colors.Normalize, optional + If ``norm`` has ``vmin`` or ``vmax`` specified, the corresponding + kwarg must be ``None``. +extend : {'neither', 'both', 'min', 'max'}, optional + How to draw arrows extending the colorbar beyond its limits. If not + provided, ``extend`` is inferred from ``vmin``, ``vmax`` and the data limits. +levels : int or array-like, optional + Split the colormap (``cmap``) into discrete color intervals. If an integer + is provided, "nice" levels are chosen based on the data range: this can + imply that the final number of levels is not exactly the expected one. + Setting ``vmin`` and/or ``vmax`` with ``levels=N`` is equivalent to + setting ``levels=np.linspace(vmin, vmax, N)``. +**kwargs : optional + Additional arguments to wrapped matplotlib function + +Returns +------- +artist : + The same type of primitive artist that the wrapped matplotlib + function returns """ # Build on the original docstring @@ -1279,124 +1279,123 @@ def scatter( def _plot2d(plotfunc): """Decorator for common 2d plotting logic.""" commondoc = """ - Parameters - ---------- - darray : DataArray - Must be two-dimensional, unless creating faceted plots. - x : Hashable or None, optional - Coordinate for *x* axis. If ``None``, use ``darray.dims[1]``. - y : Hashable or None, optional - Coordinate for *y* axis. If ``None``, use ``darray.dims[0]``. - figsize : Iterable or float or None, optional - A tuple (width, height) of the figure in inches. - Mutually exclusive with ``size`` and ``ax``. - size : scalar, optional - If provided, create a new figure for the plot with the given size: - *height* (in inches) of each plot. See also: ``aspect``. - aspect : "auto", "equal", scalar or None, optional - Aspect ratio of plot, so that ``aspect * size`` gives the *width* in - inches. Only used if a ``size`` is provided. - ax : matplotlib axes object, optional - Axes on which to plot. By default, use the current axes. - Mutually exclusive with ``size`` and ``figsize``. - row : Hashable or None, optional - If passed, make row faceted plots on this dimension name. - col : Hashable or None, optional - If passed, make column faceted plots on this dimension name. - col_wrap : int, optional - Use together with ``col`` to wrap faceted plots. - xincrease : None, True, or False, optional - Should the values on the *x* axis be increasing from left to right? - If ``None``, use the default for the Matplotlib function. - yincrease : None, True, or False, optional - Should the values on the *y* axis be increasing from top to bottom? - If ``None``, use the default for the Matplotlib function. - add_colorbar : bool, optional - Add colorbar to axes. - add_labels : bool, optional - Use xarray metadata to label axes. - vmin : float or None, optional - Lower value to anchor the colormap, otherwise it is inferred from the - data and other keyword arguments. When a diverging dataset is inferred, - setting `vmin` or `vmax` will fix the other by symmetry around - ``center``. Setting both values prevents use of a diverging colormap. - If discrete levels are provided as an explicit list, both of these - values are ignored. - vmax : float or None, optional - Upper value to anchor the colormap, otherwise it is inferred from the - data and other keyword arguments. When a diverging dataset is inferred, - setting `vmin` or `vmax` will fix the other by symmetry around - ``center``. Setting both values prevents use of a diverging colormap. - If discrete levels are provided as an explicit list, both of these - values are ignored. - cmap : matplotlib colormap name or colormap, optional - The mapping from data values to color space. If not provided, this - will be either be ``'viridis'`` (if the function infers a sequential - dataset) or ``'RdBu_r'`` (if the function infers a diverging dataset). - See :doc:`Choosing Colormaps in Matplotlib <matplotlib:users/explain/colors/colormaps>` - for more information. - - If *seaborn* is installed, ``cmap`` may also be a - `seaborn color palette <https://seaborn.pydata.org/tutorial/color_palettes.html>`_. - Note: if ``cmap`` is a seaborn color palette and the plot type - is not ``'contour'`` or ``'contourf'``, ``levels`` must also be specified. - center : float or False, optional - The value at which to center the colormap. Passing this value implies - use of a diverging colormap. Setting it to ``False`` prevents use of a - diverging colormap. - robust : bool, optional - If ``True`` and ``vmin`` or ``vmax`` are absent, the colormap range is - computed with 2nd and 98th percentiles instead of the extreme values. - extend : {'neither', 'both', 'min', 'max'}, optional - How to draw arrows extending the colorbar beyond its limits. If not - provided, ``extend`` is inferred from ``vmin``, ``vmax`` and the data limits. - levels : int or array-like, optional - Split the colormap (``cmap``) into discrete color intervals. If an integer - is provided, "nice" levels are chosen based on the data range: this can - imply that the final number of levels is not exactly the expected one. - Setting ``vmin`` and/or ``vmax`` with ``levels=N`` is equivalent to - setting ``levels=np.linspace(vmin, vmax, N)``. - infer_intervals : bool, optional - Only applies to pcolormesh. If ``True``, the coordinate intervals are - passed to pcolormesh. If ``False``, the original coordinates are used - (this can be useful for certain map projections). The default is to - always infer intervals, unless the mesh is irregular and plotted on - a map projection. - colors : str or array-like of color-like, optional - A single color or a sequence of colors. If the plot type is not ``'contour'`` - or ``'contourf'``, the ``levels`` argument is required. - subplot_kws : dict, optional - Dictionary of keyword arguments for Matplotlib subplots. Only used - for 2D and faceted plots. - (see :py:meth:`matplotlib:matplotlib.figure.Figure.add_subplot`). - cbar_ax : matplotlib axes object, optional - Axes in which to draw the colorbar. - cbar_kwargs : dict, optional - Dictionary of keyword arguments to pass to the colorbar - (see :meth:`matplotlib:matplotlib.figure.Figure.colorbar`). - xscale : {'linear', 'symlog', 'log', 'logit'} or None, optional - Specifies scaling for the x-axes. - yscale : {'linear', 'symlog', 'log', 'logit'} or None, optional - Specifies scaling for the y-axes. - xticks : ArrayLike or None, optional - Specify tick locations for x-axes. - yticks : ArrayLike or None, optional - Specify tick locations for y-axes. - xlim : tuple[float, float] or None, optional - Specify x-axes limits. - ylim : tuple[float, float] or None, optional - Specify y-axes limits. - norm : matplotlib.colors.Normalize, optional - If ``norm`` has ``vmin`` or ``vmax`` specified, the corresponding - kwarg must be ``None``. - **kwargs : optional - Additional keyword arguments to wrapped Matplotlib function. - - Returns - ------- - artist : - The same type of primitive artist that the wrapped Matplotlib - function returns. +Parameters +---------- +darray : DataArray + Must be two-dimensional, unless creating faceted plots. +x : Hashable or None, optional + Coordinate for *x* axis. If ``None``, use ``darray.dims[1]``. +y : Hashable or None, optional + Coordinate for *y* axis. If ``None``, use ``darray.dims[0]``. +figsize : Iterable or float or None, optional + A tuple (width, height) of the figure in inches. + Mutually exclusive with ``size`` and ``ax``. +size : scalar, optional + If provided, create a new figure for the plot with the given size: + *height* (in inches) of each plot. See also: ``aspect``. +aspect : "auto", "equal", scalar or None, optional + Aspect ratio of plot, so that ``aspect * size`` gives the *width* in + inches. Only used if a ``size`` is provided. +ax : matplotlib axes object, optional + Axes on which to plot. By default, use the current axes. + Mutually exclusive with ``size`` and ``figsize``. +row : Hashable or None, optional + If passed, make row faceted plots on this dimension name. +col : Hashable or None, optional + If passed, make column faceted plots on this dimension name. +col_wrap : int, optional + Use together with ``col`` to wrap faceted plots. +xincrease : None, True, or False, optional + Should the values on the *x* axis be increasing from left to right? + If ``None``, use the default for the Matplotlib function. +yincrease : None, True, or False, optional + Should the values on the *y* axis be increasing from top to bottom? + If ``None``, use the default for the Matplotlib function. +add_colorbar : bool, optional + Add colorbar to axes. +add_labels : bool, optional + Use xarray metadata to label axes. +vmin : float or None, optional + Lower value to anchor the colormap, otherwise it is inferred from the + data and other keyword arguments. When a diverging dataset is inferred, + setting `vmin` or `vmax` will fix the other by symmetry around + ``center``. Setting both values prevents use of a diverging colormap. + If discrete levels are provided as an explicit list, both of these + values are ignored. +vmax : float or None, optional + Upper value to anchor the colormap, otherwise it is inferred from the + data and other keyword arguments. When a diverging dataset is inferred, + setting `vmin` or `vmax` will fix the other by symmetry around + ``center``. Setting both values prevents use of a diverging colormap. + If discrete levels are provided as an explicit list, both of these + values are ignored. +cmap : matplotlib colormap name or colormap, optional + The mapping from data values to color space. If not provided, this + will be either be ``'viridis'`` (if the function infers a sequential + dataset) or ``'RdBu_r'`` (if the function infers a diverging dataset). + See :doc:`Choosing Colormaps in Matplotlib <matplotlib:users/explain/colors/colormaps>` + for more information. + If *seaborn* is installed, ``cmap`` may also be a + `seaborn color palette <https://seaborn.pydata.org/tutorial/color_palettes.html>`_. + Note: if ``cmap`` is a seaborn color palette and the plot type + is not ``'contour'`` or ``'contourf'``, ``levels`` must also be specified. +center : float or False, optional + The value at which to center the colormap. Passing this value implies + use of a diverging colormap. Setting it to ``False`` prevents use of a + diverging colormap. +robust : bool, optional + If ``True`` and ``vmin`` or ``vmax`` are absent, the colormap range is + computed with 2nd and 98th percentiles instead of the extreme values. +extend : {'neither', 'both', 'min', 'max'}, optional + How to draw arrows extending the colorbar beyond its limits. If not + provided, ``extend`` is inferred from ``vmin``, ``vmax`` and the data limits. +levels : int or array-like, optional + Split the colormap (``cmap``) into discrete color intervals. If an integer + is provided, "nice" levels are chosen based on the data range: this can + imply that the final number of levels is not exactly the expected one. + Setting ``vmin`` and/or ``vmax`` with ``levels=N`` is equivalent to + setting ``levels=np.linspace(vmin, vmax, N)``. +infer_intervals : bool, optional + Only applies to pcolormesh. If ``True``, the coordinate intervals are + passed to pcolormesh. If ``False``, the original coordinates are used + (this can be useful for certain map projections). The default is to + always infer intervals, unless the mesh is irregular and plotted on + a map projection. +colors : str or array-like of color-like, optional + A single color or a sequence of colors. If the plot type is not ``'contour'`` + or ``'contourf'``, the ``levels`` argument is required. +subplot_kws : dict, optional + Dictionary of keyword arguments for Matplotlib subplots. Only used + for 2D and faceted plots. + (see :py:meth:`matplotlib:matplotlib.figure.Figure.add_subplot`). +cbar_ax : matplotlib axes object, optional + Axes in which to draw the colorbar. +cbar_kwargs : dict, optional + Dictionary of keyword arguments to pass to the colorbar + (see :meth:`matplotlib:matplotlib.figure.Figure.colorbar`). +xscale : {'linear', 'symlog', 'log', 'logit'} or None, optional + Specifies scaling for the x-axes. +yscale : {'linear', 'symlog', 'log', 'logit'} or None, optional + Specifies scaling for the y-axes. +xticks : ArrayLike or None, optional + Specify tick locations for x-axes. +yticks : ArrayLike or None, optional + Specify tick locations for y-axes. +xlim : tuple[float, float] or None, optional + Specify x-axes limits. +ylim : tuple[float, float] or None, optional + Specify y-axes limits. +norm : matplotlib.colors.Normalize, optional + If ``norm`` has ``vmin`` or ``vmax`` specified, the corresponding + kwarg must be ``None``. +**kwargs : optional + Additional keyword arguments to wrapped Matplotlib function. + +Returns +------- +artist : + The same type of primitive artist that the wrapped Matplotlib + function returns. """ # Build on the original docstring diff --git a/xarray/plot/dataset_plot.py b/xarray/plot/dataset_plot.py index 341125a55ee..37bdcbac94e 100644 --- a/xarray/plot/dataset_plot.py +++ b/xarray/plot/dataset_plot.py @@ -37,119 +37,119 @@ def _dsplot(plotfunc): commondoc = """ - Parameters - ---------- - - ds : Dataset - x : Hashable or None, optional - Variable name for x-axis. - y : Hashable or None, optional - Variable name for y-axis. - u : Hashable or None, optional - Variable name for the *u* velocity (in *x* direction). - quiver/streamplot plots only. - v : Hashable or None, optional - Variable name for the *v* velocity (in *y* direction). - quiver/streamplot plots only. - hue: Hashable or None, optional - Variable by which to color scatter points or arrows. - hue_style: {'continuous', 'discrete'} or None, optional - How to use the ``hue`` variable: - - - ``'continuous'`` -- continuous color scale - (default for numeric ``hue`` variables) - - ``'discrete'`` -- a color for each unique value, using the default color cycle - (default for non-numeric ``hue`` variables) - - row : Hashable or None, optional - If passed, make row faceted plots on this dimension name. - col : Hashable or None, optional - If passed, make column faceted plots on this dimension name. - col_wrap : int, optional - Use together with ``col`` to wrap faceted plots. - ax : matplotlib axes object or None, optional - If ``None``, use the current axes. Not applicable when using facets. - figsize : Iterable[float] or None, optional - A tuple (width, height) of the figure in inches. - Mutually exclusive with ``size`` and ``ax``. - size : scalar, optional - If provided, create a new figure for the plot with the given size. - Height (in inches) of each plot. See also: ``aspect``. - aspect : "auto", "equal", scalar or None, optional - Aspect ratio of plot, so that ``aspect * size`` gives the width in - inches. Only used if a ``size`` is provided. - sharex : bool or None, optional - If True all subplots share the same x-axis. - sharey : bool or None, optional - If True all subplots share the same y-axis. - add_guide: bool or None, optional - Add a guide that depends on ``hue_style``: - - - ``'continuous'`` -- build a colorbar - - ``'discrete'`` -- build a legend - - subplot_kws : dict or None, optional - Dictionary of keyword arguments for Matplotlib subplots - (see :py:meth:`matplotlib:matplotlib.figure.Figure.add_subplot`). - Only applies to FacetGrid plotting. - cbar_kwargs : dict, optional - Dictionary of keyword arguments to pass to the colorbar - (see :meth:`matplotlib:matplotlib.figure.Figure.colorbar`). - cbar_ax : matplotlib axes object, optional - Axes in which to draw the colorbar. - cmap : matplotlib colormap name or colormap, optional - The mapping from data values to color space. Either a - Matplotlib colormap name or object. If not provided, this will - be either ``'viridis'`` (if the function infers a sequential - dataset) or ``'RdBu_r'`` (if the function infers a diverging - dataset). - See :doc:`Choosing Colormaps in Matplotlib <matplotlib:users/explain/colors/colormaps>` - for more information. - - If *seaborn* is installed, ``cmap`` may also be a - `seaborn color palette <https://seaborn.pydata.org/tutorial/color_palettes.html>`_. - Note: if ``cmap`` is a seaborn color palette, - ``levels`` must also be specified. - vmin : float or None, optional - Lower value to anchor the colormap, otherwise it is inferred from the - data and other keyword arguments. When a diverging dataset is inferred, - setting `vmin` or `vmax` will fix the other by symmetry around - ``center``. Setting both values prevents use of a diverging colormap. - If discrete levels are provided as an explicit list, both of these - values are ignored. - vmax : float or None, optional - Upper value to anchor the colormap, otherwise it is inferred from the - data and other keyword arguments. When a diverging dataset is inferred, - setting `vmin` or `vmax` will fix the other by symmetry around - ``center``. Setting both values prevents use of a diverging colormap. - If discrete levels are provided as an explicit list, both of these - values are ignored. - norm : matplotlib.colors.Normalize, optional - If ``norm`` has ``vmin`` or ``vmax`` specified, the corresponding - kwarg must be ``None``. - infer_intervals: bool | None - If True the intervals are inferred. - center : float, optional - The value at which to center the colormap. Passing this value implies - use of a diverging colormap. Setting it to ``False`` prevents use of a - diverging colormap. - robust : bool, optional - If ``True`` and ``vmin`` or ``vmax`` are absent, the colormap range is - computed with 2nd and 98th percentiles instead of the extreme values. - colors : str or array-like of color-like, optional - A single color or a list of colors. The ``levels`` argument - is required. - extend : {'neither', 'both', 'min', 'max'}, optional - How to draw arrows extending the colorbar beyond its limits. If not - provided, ``extend`` is inferred from ``vmin``, ``vmax`` and the data limits. - levels : int or array-like, optional - Split the colormap (``cmap``) into discrete color intervals. If an integer - is provided, "nice" levels are chosen based on the data range: this can - imply that the final number of levels is not exactly the expected one. - Setting ``vmin`` and/or ``vmax`` with ``levels=N`` is equivalent to - setting ``levels=np.linspace(vmin, vmax, N)``. - **kwargs : optional - Additional keyword arguments to wrapped Matplotlib function. +Parameters +---------- + +ds : Dataset +x : Hashable or None, optional + Variable name for x-axis. +y : Hashable or None, optional + Variable name for y-axis. +u : Hashable or None, optional + Variable name for the *u* velocity (in *x* direction). + quiver/streamplot plots only. +v : Hashable or None, optional + Variable name for the *v* velocity (in *y* direction). + quiver/streamplot plots only. +hue: Hashable or None, optional + Variable by which to color scatter points or arrows. +hue_style: {'continuous', 'discrete'} or None, optional + How to use the ``hue`` variable: + + - ``'continuous'`` -- continuous color scale + (default for numeric ``hue`` variables) + - ``'discrete'`` -- a color for each unique value, using the default color cycle + (default for non-numeric ``hue`` variables) + +row : Hashable or None, optional + If passed, make row faceted plots on this dimension name. +col : Hashable or None, optional + If passed, make column faceted plots on this dimension name. +col_wrap : int, optional + Use together with ``col`` to wrap faceted plots. +ax : matplotlib axes object or None, optional + If ``None``, use the current axes. Not applicable when using facets. +figsize : Iterable[float] or None, optional + A tuple (width, height) of the figure in inches. + Mutually exclusive with ``size`` and ``ax``. +size : scalar, optional + If provided, create a new figure for the plot with the given size. + Height (in inches) of each plot. See also: ``aspect``. +aspect : "auto", "equal", scalar or None, optional + Aspect ratio of plot, so that ``aspect * size`` gives the width in + inches. Only used if a ``size`` is provided. +sharex : bool or None, optional + If True all subplots share the same x-axis. +sharey : bool or None, optional + If True all subplots share the same y-axis. +add_guide: bool or None, optional + Add a guide that depends on ``hue_style``: + + - ``'continuous'`` -- build a colorbar + - ``'discrete'`` -- build a legend + +subplot_kws : dict or None, optional + Dictionary of keyword arguments for Matplotlib subplots + (see :py:meth:`matplotlib:matplotlib.figure.Figure.add_subplot`). + Only applies to FacetGrid plotting. +cbar_kwargs : dict, optional + Dictionary of keyword arguments to pass to the colorbar + (see :meth:`matplotlib:matplotlib.figure.Figure.colorbar`). +cbar_ax : matplotlib axes object, optional + Axes in which to draw the colorbar. +cmap : matplotlib colormap name or colormap, optional + The mapping from data values to color space. Either a + Matplotlib colormap name or object. If not provided, this will + be either ``'viridis'`` (if the function infers a sequential + dataset) or ``'RdBu_r'`` (if the function infers a diverging + dataset). + See :doc:`Choosing Colormaps in Matplotlib <matplotlib:users/explain/colors/colormaps>` + for more information. + + If *seaborn* is installed, ``cmap`` may also be a + `seaborn color palette <https://seaborn.pydata.org/tutorial/color_palettes.html>`_. + Note: if ``cmap`` is a seaborn color palette, + ``levels`` must also be specified. +vmin : float or None, optional + Lower value to anchor the colormap, otherwise it is inferred from the + data and other keyword arguments. When a diverging dataset is inferred, + setting `vmin` or `vmax` will fix the other by symmetry around + ``center``. Setting both values prevents use of a diverging colormap. + If discrete levels are provided as an explicit list, both of these + values are ignored. +vmax : float or None, optional + Upper value to anchor the colormap, otherwise it is inferred from the + data and other keyword arguments. When a diverging dataset is inferred, + setting `vmin` or `vmax` will fix the other by symmetry around + ``center``. Setting both values prevents use of a diverging colormap. + If discrete levels are provided as an explicit list, both of these + values are ignored. +norm : matplotlib.colors.Normalize, optional + If ``norm`` has ``vmin`` or ``vmax`` specified, the corresponding + kwarg must be ``None``. +infer_intervals: bool | None + If True the intervals are inferred. +center : float, optional + The value at which to center the colormap. Passing this value implies + use of a diverging colormap. Setting it to ``False`` prevents use of a + diverging colormap. +robust : bool, optional + If ``True`` and ``vmin`` or ``vmax`` are absent, the colormap range is + computed with 2nd and 98th percentiles instead of the extreme values. +colors : str or array-like of color-like, optional + A single color or a list of colors. The ``levels`` argument + is required. +extend : {'neither', 'both', 'min', 'max'}, optional + How to draw arrows extending the colorbar beyond its limits. If not + provided, ``extend`` is inferred from ``vmin``, ``vmax`` and the data limits. +levels : int or array-like, optional + Split the colormap (``cmap``) into discrete color intervals. If an integer + is provided, "nice" levels are chosen based on the data range: this can + imply that the final number of levels is not exactly the expected one. + Setting ``vmin`` and/or ``vmax`` with ``levels=N`` is equivalent to + setting ``levels=np.linspace(vmin, vmax, N)``. +**kwargs : optional + Additional keyword arguments to wrapped Matplotlib function. """ # Build on the original docstring