From 8d4163d58a8e6d3571519efe84c91e312e9a6e23 Mon Sep 17 00:00:00 2001 From: Nicolas Kruchten Date: Mon, 16 Dec 2019 21:28:39 -0500 Subject: [PATCH 01/10] Closes https://github.com/plotly/documentation/issues/1629 --- doc/python/annotated_heatmap.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/doc/python/annotated_heatmap.md b/doc/python/annotated_heatmap.md index e00b9b697ad..9a4a1312a98 100644 --- a/doc/python/annotated_heatmap.md +++ b/doc/python/annotated_heatmap.md @@ -29,7 +29,8 @@ jupyter: name: Annotated Heatmaps order: 8 page_type: u-guide - permalink: python/annotated_heatmap/ + permalink: python/annotated-heatmap/ + redirect_from: python/annotated_heatmap/ thumbnail: thumbnail/ann_heat.jpg --- From c3b7ba0b2ee1428387088fdbd1cab3ac06b98b55 Mon Sep 17 00:00:00 2001 From: Nicolas Kruchten Date: Mon, 16 Dec 2019 21:40:30 -0500 Subject: [PATCH 02/10] Rename annotated_heatmap.md to annotated-heatmap.md --- doc/python/{annotated_heatmap.md => annotated-heatmap.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename doc/python/{annotated_heatmap.md => annotated-heatmap.md} (100%) diff --git a/doc/python/annotated_heatmap.md b/doc/python/annotated-heatmap.md similarity index 100% rename from doc/python/annotated_heatmap.md rename to doc/python/annotated-heatmap.md From a3d2aff45bc8f7ec742376771f93952ff076335a Mon Sep 17 00:00:00 2001 From: Nicolas Kruchten Date: Tue, 17 Dec 2019 10:44:09 -0500 Subject: [PATCH 03/10] standardize on df variable name --- doc/python/3d-bubble-charts.md | 15 +- doc/python/3d-line-plots.md | 13 +- doc/python/3d-scatter-plots.md | 16 +- doc/python/animations.md | 27 ++-- doc/python/axes.md | 109 ++++++++------ doc/python/bar-charts.md | 18 +-- doc/python/box-plots.md | 48 +++--- doc/python/bubble-charts.md | 8 +- doc/python/bubble-maps.md | 13 +- doc/python/choropleth-maps.md | 9 +- doc/python/colorscales.md | 29 ++-- doc/python/creating-and-updating-figures.md | 114 +++++++------- doc/python/distplot.md | 15 +- doc/python/error-bars.md | 17 ++- doc/python/facet-plots.md | 21 ++- doc/python/filled-area-plots.md | 8 +- doc/python/histograms.md | 53 +++---- doc/python/horizontal-bar-charts.md | 15 +- doc/python/hover-text-and-formatting.md | 18 ++- doc/python/line-and-scatter.md | 21 ++- doc/python/line-charts.md | 27 ++-- doc/python/linear-fits.md | 18 +-- doc/python/lines-on-maps.md | 7 +- doc/python/marker-style.md | 11 +- doc/python/parallel-categories-diagram.md | 30 ++-- doc/python/parallel-coordinates-plot.md | 14 +- doc/python/plotly-express.md | 155 ++++++++++---------- doc/python/polar-chart.md | 20 +-- doc/python/px-arguments.md | 29 ++-- doc/python/scatter-plots-on-maps.md | 16 +- doc/python/scattermapbox.md | 10 +- doc/python/setting-graph-size.md | 10 +- doc/python/splom.md | 25 ++-- doc/python/templates.md | 74 ++++++---- doc/python/text-and-annotations.md | 11 +- doc/python/violin.md | 23 +-- doc/python/wind-rose-charts.md | 9 +- 37 files changed, 574 insertions(+), 502 deletions(-) diff --git a/doc/python/3d-bubble-charts.md b/doc/python/3d-bubble-charts.md index 44c901e9175..861551a9e1a 100644 --- a/doc/python/3d-bubble-charts.md +++ b/doc/python/3d-bubble-charts.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.2.3 kernelspec: display_name: Python 3 @@ -22,7 +22,8 @@ jupyter: pygments_lexer: ipython3 version: 3.7.3 plotly: - description: How to make 3D Bubble Charts in Python with Plotly. Three examples + description: + How to make 3D Bubble Charts in Python with Plotly. Three examples of 3D Bubble Charts. display_as: 3d_charts language: python @@ -39,15 +40,13 @@ jupyter: ```python import plotly.express as px import numpy as np -gapminder = px.data.gapminder() -#gapminder.columns -fig = px.scatter_3d(gapminder, x='year', y='continent', z='pop', size='gdpPercap', color='lifeExp', +df = px.data.gapminder() +fig = px.scatter_3d(df, x='year', y='continent', z='pop', size='gdpPercap', color='lifeExp', hover_data=['country']) fig.update_layout(scene_zaxis_type="log") fig.show() ``` - #### Simple Bubble Chart ```python @@ -85,6 +84,7 @@ fig.show() ``` #### Bubble Chart Sized by a Variable + Plot planets' distance from sun, density, and gravity with bubble size based on planet size ```python @@ -125,6 +125,7 @@ fig.show() ``` #### Edit the Colorbar + Plot planets' distance from sun, density, and gravity with bubble size based on planet size ```python @@ -165,5 +166,5 @@ fig.show() ``` #### Reference -See https://plot.ly/python/reference/#scatter3d and https://plot.ly/python/reference/#scatter-marker-sizeref
for more information and chart attribute options! +See https://plot.ly/python/reference/#scatter3d and https://plot.ly/python/reference/#scatter-marker-sizeref
for more information and chart attribute options! diff --git a/doc/python/3d-line-plots.md b/doc/python/3d-line-plots.md index 83f0baf4136..0861b9760a4 100644 --- a/doc/python/3d-line-plots.md +++ b/doc/python/3d-line-plots.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.2.3 kernelspec: display_name: Python 3 @@ -38,20 +38,19 @@ jupyter: ```python import plotly.express as px import plotly.express as px -gapminder = px.data.gapminder().query("country=='Brazil'") -fig = px.line_3d(gapminder, x="gdpPercap", y="pop", z="year") +df = px.data.gapminder().query("country=='Brazil'") +fig = px.line_3d(df, x="gdpPercap", y="pop", z="year") fig.show() ``` ```python import plotly.express as px import plotly.express as px -gapminder = px.data.gapminder().query("continent=='Europe'") -fig = px.line_3d(gapminder, x="gdpPercap", y="pop", z="year", color='country') +df = px.data.gapminder().query("continent=='Europe'") +fig = px.line_3d(df, x="gdpPercap", y="pop", z="year", color='country') fig.show() ``` - #### 3D Line Plot of Brownian Motion Here we represent a trajectory in 3D. @@ -120,5 +119,5 @@ fig.show() ``` #### Reference -See https://plot.ly/python/reference/#scatter3d-marker-line for more information and chart attribute options! +See https://plot.ly/python/reference/#scatter3d-marker-line for more information and chart attribute options! diff --git a/doc/python/3d-scatter-plots.md b/doc/python/3d-scatter-plots.md index 436ffc6b736..0d5beba1bb8 100644 --- a/doc/python/3d-scatter-plots.md +++ b/doc/python/3d-scatter-plots.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.1 kernelspec: display_name: Python 3 @@ -41,8 +41,8 @@ Like the [2D scatter plot](https://plot.ly/python/line-and-scatter/) `px.scatter ```python import plotly.express as px -iris = px.data.iris() -fig = px.scatter_3d(iris, x='sepal_length', y='sepal_width', z='petal_width', +df = px.data.iris() +fig = px.scatter_3d(df, x='sepal_length', y='sepal_width', z='petal_width', color='species') fig.show() ``` @@ -51,8 +51,8 @@ A 4th dimension of the data can be represented thanks to the color of the marker ```python import plotly.express as px -iris = px.data.iris() -fig = px.scatter_3d(iris, x='sepal_length', y='sepal_width', z='petal_width', +df = px.data.iris() +fig = px.scatter_3d(df, x='sepal_length', y='sepal_width', z='petal_width', color='petal_length', symbol='species') fig.show() ``` @@ -63,8 +63,8 @@ It is possible to customize the style of the figure through the parameters of `p ```python import plotly.express as px -iris = px.data.iris() -fig = px.scatter_3d(iris, x='sepal_length', y='sepal_width', z='petal_width', +df = px.data.iris() +fig = px.scatter_3d(df, x='sepal_length', y='sepal_width', z='petal_width', color='petal_length', size='petal_length', size_max=18, symbol='species', opacity=0.7) @@ -122,7 +122,6 @@ fig.show() ### Dash App - [Dash](https://plot.ly/products/dash/) is an Open Source Python library which can help you convert plotly figures into a reactive, web-based application. Below is a simple example of a dashboard created using Dash. Its [source code](https://github.com/plotly/simple-example-chart-apps/tree/master/dash-3dscatterplot) can easily be deployed to a PaaS. ```python @@ -136,4 +135,5 @@ IFrame(src= "https://dash-simple-apps.plotly.host/dash-3dscatterplot/code", widt ``` #### Reference + See https://plot.ly/python/reference/#scatter3d for more information and chart attribute options! diff --git a/doc/python/animations.md b/doc/python/animations.md index 1e3c0cd5cd8..bf8e21dd230 100644 --- a/doc/python/animations.md +++ b/doc/python/animations.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.6 kernelspec: display_name: Python 3 @@ -24,28 +24,29 @@ jupyter: --- #### Animated figures with Plotly Express + Several Plotly Express functions support the creation of animated figures through the `animation_frame` and `animation_group` arguments. Here is an example of an animated scatter plot creating using Plotly Express. Note that you should always fix the `x_range` and `y_range` to ensure that your data remains visible throughout the animation. ```python import plotly.express as px -gapminder = px.data.gapminder() -px.scatter(gapminder, x="gdpPercap", y="lifeExp", animation_frame="year", animation_group="country", +df = px.data.gapminder() +px.scatter(df, x="gdpPercap", y="lifeExp", animation_frame="year", animation_group="country", size="pop", color="continent", hover_name="country", log_x=True, size_max=55, range_x=[100,100000], range_y=[25,90]) ``` #### Animated Bar Charts with Plotly Express - Note that you should always fix the `y_range` to ensure that your data remains visible throughout the animation. +Note that you should always fix the `y_range` to ensure that your data remains visible throughout the animation. ```python import plotly.express as px -gapminder = px.data.gapminder() +df = px.data.gapminder() -fig = px.bar(gapminder, x="continent", y="pop", color="continent", +fig = px.bar(df, x="continent", y="pop", color="continent", animation_frame="year", animation_group="country", range_y=[0,4000000000]) fig.show() ``` @@ -54,32 +55,36 @@ fig.show() The remainder of this section describes the low-level API for constructing animated figures manually. - #### Frames + Along with `data` and `layout`, `frames` can be added as a key in a figure object. The `frames` key points to a list of figures, each of which will be cycled through when animation is triggered. + #### Adding Control Buttons to Animations + You can add play and pause buttons to control your animated charts by adding an `updatemenus` array to the `layout` of your `figure`. More information on style and placement of the buttons is available in Plotly's [`updatemenus` reference](https://plot.ly/python/reference/#layout-updatemenus).
The buttons are defined as follows: + ``` "updatemenus": [{"type": "buttons", "buttons": [{"label": "Your Label", "method": "animate", "args": [See Below]}]}] ``` + #### Defining Button Arguments + - `None`: Setting `"args"` to undefined (i.e. `"args": [None]`) will create a simple play button that will animate all frames. - string: Animate all frames with group `""`. This is a way of scoping the animations in case you would prefer to animate without explicitly enumerating all frames. - `["frame1", "frame2", ...]`: Animate a sequence of named frames. - `[{data: [], layout: {}, traces: []}, {...}]`: Nearly identical to animating named frames; though this variant lets you inline data instead of adding it as named frames. This can be useful for interaction where it's undesirable to add and manage named frames for ephemeral changes. - `[null]`: A simple way to create a pause button (requires `mode: "immediate"`). This argument dumps the currently queued frames (`mode: "immediate"`), and then animates an empty sequence of frames (`[null]`). - Please Note: We do not recommend using: `[ ]`. This syntax may cause confusion because it looks indistinguishable from a "pause button", but nested properties have logic that treats empty arrays as entirely removable, so it will function as a play button.

-Refer to the examples below to see the buttons in action! - + Refer to the examples below to see the buttons in action! #### Simple Play Button @@ -224,6 +229,7 @@ fig.show() ``` #### Using a Slider and Buttons + The following example uses the well known [Gapminder dataset](https://www.gapminder.org/tag/gdp-per-capita/) to exemplify animation capabilities. This bubble chart animation shows the change in 'GDP per Capita' against the 'Life Expectancy' of several countries from the year 1952 to 2007, colored by their respective continent and sized by population. This is also an example of building up the structure of a figure as a Python dictionary, and then constructing a graph object figure from that dictionary. @@ -378,9 +384,10 @@ fig.show() ``` #### Important Notes -- Defining `redraw`: Setting `redraw: false` is an optimization for scatter plots so that animate just makes changes without redrawing the whole plot. For other plot types, such as contour plots, every frame must be a total plot redraw, i.e. `redraw: true`. +- Defining `redraw`: Setting `redraw: false` is an optimization for scatter plots so that animate just makes changes without redrawing the whole plot. For other plot types, such as contour plots, every frame must be a total plot redraw, i.e. `redraw: true`. #### Reference + For additional information and attributes for creating bubble charts in Plotly see: https://plot.ly/python/bubble-charts/. For more documentation on creating animations with Plotly, see https://plot.ly/python/#animations. diff --git a/doc/python/axes.md b/doc/python/axes.md index 6bcb6a1c159..a39533cbdb3 100644 --- a/doc/python/axes.md +++ b/doc/python/axes.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.2.1 kernelspec: display_name: Python 3 @@ -22,7 +22,8 @@ jupyter: pygments_lexer: ipython3 version: 3.7.3 plotly: - description: How to adjust axes properties in python. Includes examples of linear + description: + How to adjust axes properties in python. Includes examples of linear and logarithmic axes, axes titles, styling and coloring axes and grid lines, and more. display_as: file_settings @@ -37,7 +38,9 @@ jupyter: **See also** the tutorials on [subplots](/python/subplots) and [multiple axes](/python/multiple-axes/). #### Toggling Axes Lines, Ticks, Labels, and Autorange + ##### Toggling Axis grid lines + Axis grid lines can be disabled by setting the `showgrid` property to `False` for the x and/or y axis. Here is an example of setting `showgrid` to `False` in the graph object figure constructor. @@ -94,16 +97,15 @@ fig.show() ##### Toggle grid and zerolines for figure created with Plotly Express - -An advantage of using the `update_xaxis` and `update_yaxis` methods is that these updates will (by default) apply to all axes in the figure. This is especially useful when customizing figures created using Plotly Express, figure factories, or `make_subplots`. +An advantage of using the `update_xaxis` and `update_yaxis` methods is that these updates will (by default) apply to all axes in the figure. This is especially useful when customizing figures created using Plotly Express, figure factories, or `make_subplots`. Here is an example of disabling all grid and zero lines in a faceted figure created by Plotly Express. ```python import plotly.express as px -iris = px.data.iris() +df = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length", facet_col="species") +fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_xaxes(showgrid=False, zeroline=False) fig.update_yaxes(showgrid=False, zeroline=False) @@ -111,15 +113,16 @@ fig.show() ``` ##### Toggling axis tick marks + Axis tick marks are disabled by default for the default `plotly` theme, but they can easily be turned on by setting the `ticks` axis property to `"inside"` (to place ticks inside plotting area) or `"outside"` (to place ticks outside the plotting area). Here is an example of turning on inside x-axis and y-axis ticks in a faceted figure created using Plotly Express. Note how the `col` argument to `update_yaxes` is used to only turn on the y-axis ticks for the left-most subplot. ```python import plotly.express as px -iris = px.data.iris() +df = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length", facet_col="species") +fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_xaxes(ticks="inside") fig.update_yaxes(ticks="inside", col=1) @@ -127,15 +130,16 @@ fig.show() ``` ##### Toggling axis labels + The axis tick mark labels can be disabled by setting the `showticklabels` axis property to `False`. Here is an example of disabling tick labels in all subplots for a faceted figure created using Plotly Express. ```python import plotly.express as px -iris = px.data.iris() +df = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length", facet_col="species") +fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_xaxes(showticklabels=False) fig.update_yaxes(showticklabels=False) @@ -145,62 +149,66 @@ fig.show() #### Tick Placement, Color, and Style ##### Set number of tick marks + The approximate number of ticks displayed for an axis can be specified using the `nticks` axis property. Here is an example of updating the y-axes of a figure created using Plotly Express to display approximately 20 ticks. ```python import plotly.express as px -iris = px.data.iris() +df = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length", facet_col="species") +fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_yaxes(nticks=20) fig.show() ``` ##### Set start position and distance between ticks -The `tick0` and `dtick` axis properties can be used to control to placement of axis ticks as follows: If specified, a tick will fall exactly on the location of `tick0` and additional ticks will be added in both directions at intervals of `dtick`. + +The `tick0` and `dtick` axis properties can be used to control to placement of axis ticks as follows: If specified, a tick will fall exactly on the location of `tick0` and additional ticks will be added in both directions at intervals of `dtick`. Here is an example of updating the y axis of a figure created using Plotly Express to position the ticks at intervals of 0.5, starting at 0.25. ```python import plotly.express as px -iris = px.data.iris() +df = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length", facet_col="species") +fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_yaxes(tick0=0.25, dtick=0.5) fig.show() ``` ##### Set exact location of axis ticks + It is possible to configure an axis to display ticks at a set of predefined locations by setting the `tickvals` property to an array of positions. Here is an example of setting the exact location of ticks on the y axes of a figure created using Plotly Express. ```python import plotly.express as px -iris = px.data.iris() +df = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length", facet_col="species") +fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_yaxes(tickvals=[5.1, 5.9, 6.3, 7.5]) fig.show() ``` ##### Style tick marks + As discussed above, tick marks are disabled by default in the default `plotly` theme, but they can be enabled by setting the `ticks` axis property to `"inside"` (to place ticks inside plotting area) or `"outside"` (to place ticks outside the plotting area). The appearance of these tick marks can be customized by setting their length (`ticklen`), width (`tickwidth`), and color (`tickcolor`). -Here is an example of enabling and styling the tick marks of a faceted figure created using Plotly Express. Note how the `col` argument to `update_yaxes` is used to only turn on and style the y-axis ticks for the left-most subplot. +Here is an example of enabling and styling the tick marks of a faceted figure created using Plotly Express. Note how the `col` argument to `update_yaxes` is used to only turn on and style the y-axis ticks for the left-most subplot. ```python import plotly.express as px -iris = px.data.iris() +df = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length", facet_col="species") +fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_xaxes(ticks="outside", tickwidth=2, tickcolor='crimson', ticklen=10) fig.update_yaxes(ticks="outside", tickwidth=2, tickcolor='crimson', ticklen=10, col=1) @@ -210,7 +218,8 @@ fig.show() #### Set and Style Axes Title Labels and Ticks ##### Set axis title text -Axis titles are set using the nested `title.text` property of the x or y axis. Here is an example of creating a new figure and using `update_xaxes` and `update_yaxes`, with magic underscore notation, to set the axis titles. + +Axis titles are set using the nested `title.text` property of the x or y axis. Here is an example of creating a new figure and using `update_xaxes` and `update_yaxes`, with magic underscore notation, to set the axis titles. ```python import plotly.graph_objects as go @@ -250,13 +259,14 @@ fig.show() ``` ##### Set axis title font + Here is an example that configures the font family, size, and color for the axis titles in a figure created using Plotly Express. ```python import plotly.express as px -iris = px.data.iris() +df = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length", facet_col="species") +fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_xaxes(title_font=dict(size=18, family='Courier', color='crimson')) fig.update_yaxes(title_font=dict(size=18, family='Courier', color='crimson')) @@ -264,15 +274,16 @@ fig.show() ``` ##### Set axis label rotation and font -The orientation of the axis tick mark labels is configured using the `tickangle` axis property. The value of `tickangle` is the angle of rotation, in the clockwise direction, of the labels from vertical in units of degrees. The font family, size, and color for the tick labels are stored under the `tickfont` axis property. + +The orientation of the axis tick mark labels is configured using the `tickangle` axis property. The value of `tickangle` is the angle of rotation, in the clockwise direction, of the labels from vertical in units of degrees. The font family, size, and color for the tick labels are stored under the `tickfont` axis property. Here is an example of rotating the x-axis tick labels by 45 degrees, and customizing their font properties, in a faceted histogram figure created using Plotly Express. ```python import plotly.express as px -tips = px.data.tips() +df = px.data.tips() -fig = px.histogram(tips, x="sex", y="tip", histfunc='sum', facet_col='smoker') +fig = px.histogram(df, x="sex", y="tip", histfunc='sum', facet_col='smoker') fig.update_xaxes(tickangle=45, tickfont=dict(family='Rockwell', color='crimson', size=14)) fig.show() @@ -280,17 +291,17 @@ fig.show() #### Styling and Coloring Axes and the Zero-Line - ##### Styling axis lines + The `showline` axis property controls the visibility of the axis line, and the `linecolor` and `linewidth` axis properties control the color and width of the axis line. Here is an example of enabling the x and y axis lines, and customizing their width and color, for a faceted histogram created with Plotly Express. ```python import plotly.express as px -tips = px.data.tips() +df = px.data.tips() -fig = px.histogram(tips, x="sex", y="tip", histfunc='sum', facet_col='smoker') +fig = px.histogram(df, x="sex", y="tip", histfunc='sum', facet_col='smoker') fig.update_xaxes(showline=True, linewidth=2, linecolor='black') fig.update_yaxes(showline=True, linewidth=2, linecolor='black') @@ -298,15 +309,16 @@ fig.show() ``` ##### Mirroring axis lines + Axis lines can be mirrored to the opposite side of the plotting area by setting the `mirror` axis property to `True`. Here is an example of mirroring the x and y axis lines in a faceted histogram created using Plotly Express. ```python import plotly.express as px -tips = px.data.tips() +df = px.data.tips() -fig = px.histogram(tips, x="sex", y="tip", histfunc='sum', facet_col='smoker') +fig = px.histogram(df, x="sex", y="tip", histfunc='sum', facet_col='smoker') fig.update_xaxes(showline=True, linewidth=2, linecolor='black', mirror=True) fig.update_yaxes(showline=True, linewidth=2, linecolor='black', mirror=True) @@ -314,15 +326,16 @@ fig.show() ``` ##### Styling grid lines + The width and color of axis grid lines are controlled by the `gridwidth` and `gridcolor` axis properties. Here is an example of customizing the grid line width and color for a faceted scatter plot created with Plotly Express ```python import plotly.express as px -iris = px.data.iris() +df = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length", facet_col="species") +fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_xaxes(showgrid=True, gridwidth=1, gridcolor='LightPink') fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor='LightPink') @@ -330,6 +343,7 @@ fig.show() ``` ##### Styling zero lines + The width and color of axis zero lines are controlled by the `zerolinewidth` and `zerolinecolor` axis properties. Here is an example of configuring the zero line width and color for a simple figure using the `update_xaxes` and `update_yaxes` graph object figure methods. @@ -348,15 +362,16 @@ fig.show() ``` #### Setting the Range of Axes Manually -The visible x and y axis range can be configured manually by setting the `range` axis property to a list of two values, the lower and upper boundary. + +The visible x and y axis range can be configured manually by setting the `range` axis property to a list of two values, the lower and upper boundary. Here's an example of manually specifying the x and y axis range for a faceted scatter plot created with Plotly Express. ```python import plotly.express as px -iris = px.data.iris() +df = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length", facet_col="species") +fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_xaxes(range=[1.5, 4.5]) fig.update_yaxes(range=[3, 9]) @@ -364,6 +379,7 @@ fig.show() ``` #### Subcategory Axes + A two-level categorical axis can be created by specifying a trace's `x` or `y` property as a 2-dimensional lists. The first sublist represents the outer categorical value while the second sublist represents the inner categorical value. Here is an example that creates a figure with 4 horizontal `box` traces with a 2-level categorical y-axis. @@ -437,6 +453,7 @@ fig.show() ``` ### Fixed Ratio Axes + The `scaleanchor` and `scaleratio` axis properties can be used to force a fixed ratio of pixels per unit between two axes. Here is an example of anchoring the scale of the x and y axis with a scale ratio of 1. Notice how the zoom box is constrained to prevent the distortion of the shape of the line plot. @@ -465,30 +482,32 @@ fig.show() ``` #### Reversed Axes + You can tell plotly's automatic axis range calculation logic to reverse the direction of an axis by setting the `autorange` axis property to `"reversed"`. Here is an example of reversing the direction of the y axes for a faceted scatter plot created using Plotly Express. ```python import plotly.express as px -iris = px.data.iris() +df = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length", facet_col="species") +fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_yaxes(autorange="reversed") fig.show() ``` #### Reversed Axes with Range ( Min/Max ) Specified + The direction of an axis can be reversed when manually setting the range extents by specifying a list containing the upper bound followed by the lower bound (rather that the lower followed by the upper) as the `range` axis property. Here is an example of manually setting the reversed range of the y axes in a faceted scatter plot figure created using Plotly Express. ```python import plotly.express as px -iris = px.data.iris() +df = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length", facet_col="species") +fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_yaxes(range=[9, 3]) fig.show() @@ -498,15 +517,15 @@ fig.show() The axis auto-range calculation logic can be configured using the `rangemode` axis parameter. -If `rangemode` is `"normal"` (the default), the range is computed based on the min and max values of the input data. If `"tozero"`, the the range will always include zero. If `"nonnegative"`, the range will not extend below zero, regardless of the input data. +If `rangemode` is `"normal"` (the default), the range is computed based on the min and max values of the input data. If `"tozero"`, the the range will always include zero. If `"nonnegative"`, the range will not extend below zero, regardless of the input data. Here is an example of configuring a faceted scatter plot created using Plotly Express to always include zero for both the x and y axes. ```python import plotly.express as px -iris = px.data.iris() +df = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length", facet_col="species") +fig = px.scatter(df, x="sepal_width", y="sepal_length", facet_col="species") fig.update_xaxes(rangemode="tozero") fig.update_yaxes(rangemode="tozero") @@ -514,7 +533,8 @@ fig.show() ``` #### Enumerated Ticks with Tickvals and Ticktext -The `tickvals` and `ticktext` axis properties can be used together to display custom tick label text at custom locations along an axis. They should be set to lists of the same length where the `tickvals` list contains positions along the axis, and `ticktext` contains the strings that should be displayed at the corresponding positions. + +The `tickvals` and `ticktext` axis properties can be used together to display custom tick label text at custom locations along an axis. They should be set to lists of the same length where the `tickvals` list contains positions along the axis, and `ticktext` contains the strings that should be displayed at the corresponding positions. Here is an example. @@ -555,4 +575,5 @@ fig.show() ``` #### Reference + See https://plot.ly/python/reference/#layout-xaxis and https://plot.ly/python/reference/#layout-yaxis for more information and chart attribute options! diff --git a/doc/python/bar-charts.md b/doc/python/bar-charts.md index 7928f9489a7..9386eb4d522 100644 --- a/doc/python/bar-charts.md +++ b/doc/python/bar-charts.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.1 kernelspec: display_name: Python 3 @@ -35,7 +35,6 @@ jupyter: ### Bar chart with Plotly Express - [Plotly Express](/python/plotly-express/) is the easy-to-use, high-level interface to Plotly, which [operates on "tidy" data](/python/px-arguments/). With `px.bar`, each row of the DataFrame is represented as a rectangular mark. @@ -70,15 +69,15 @@ When several rows share the same value of `x` (here Female or Male), the rectang ```python import plotly.express as px -tips = px.data.tips() -fig = px.bar(tips, x="sex", y="total_bill", color='time') +df = px.data.tips() +fig = px.bar(df, x="sex", y="total_bill", color='time') fig.show() ``` ```python # Change the default stacking import plotly.express as px -fig = px.bar(tips, x="sex", y="total_bill", color='smoker', barmode='group', +fig = px.bar(df, x="sex", y="total_bill", color='smoker', barmode='group', height=400) fig.show() ``` @@ -89,15 +88,14 @@ Use the keyword arguments `facet_row` (resp. `facet_col`) to create facetted sub ```python import plotly.express as px -fig = px.bar(tips, x="sex", y="total_bill", color="smoker", barmode="group", +fig = px.bar(df, x="sex", y="total_bill", color="smoker", barmode="group", facet_row="time", facet_col="day", category_orders={"day": ["Thur", "Fri", "Sat", "Sun"], "time": ["Lunch", "Dinner"]}) fig.show() ``` -To learn more, see the *link to px.bar reference page*. - +To learn more, see the _link to px.bar reference page_. #### Basic Bar Chart with plotly.graph_objects @@ -239,7 +237,6 @@ fig.show() ### Customizing Individual Bar Base - ```python import plotly.graph_objects as go @@ -373,10 +370,8 @@ fig.show() See examples of horizontal bar charts [here](https://plot.ly/python/horizontal-bar-charts/). - ### Dash Example - [Dash](https://plot.ly/products/dash/) is an Open Source Python library which can help you convert plotly figures into a reactive, web-based application. Below is a simple example of a dashboard created using Dash. Its [source code](https://github.com/plotly/simple-example-chart-apps/tree/master/dash-barplot) is also show below and can easily be deployed to a PaaS (platform as a service). ```python @@ -391,4 +386,5 @@ IFrame(src= "https://dash-simple-apps.plotly.host/dash-barplot/code", width="80% ``` ### Reference + See https://plot.ly/python/reference/#bar for more information and chart attribute options! diff --git a/doc/python/box-plots.md b/doc/python/box-plots.md index d92a175a946..118b780ed4b 100644 --- a/doc/python/box-plots.md +++ b/doc/python/box-plots.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.1 kernelspec: display_name: Python 3 @@ -31,25 +31,23 @@ jupyter: page_type: example_index permalink: python/box-plots/ thumbnail: thumbnail/box.jpg - redirect_from: + redirect_from: - /python/box/ - /python/basic_statistics/ --- A [box plot](https://en.wikipedia.org/wiki/Box_plot) is a statistical representation of numerical data through their quartiles. The ends of the box represent the lower and upper quartiles, while the median (second quartile) is marked by a line inside the box. For other statistical representations of numerical data, see [other statistical charts](https://plot.ly/python/statistical-charts/). - ## Box Plot with `plotly.express` [Plotly Express](/python/plotly-express/) is the easy-to-use, high-level interface to Plotly, which [operates on "tidy" data](/python/px-arguments/). In a box plot created by `px.box`, the distribution of the column given as `y` argument is represented. - ```python import plotly.express as px -tips = px.data.tips() -fig = px.box(tips, y="total_bill") +df = px.data.tips() +fig = px.box(df, y="total_bill") fig.show() ``` @@ -57,8 +55,8 @@ If a column name is given as `x` argument, a box plot is drawn for each value of ```python import plotly.express as px -tips = px.data.tips() -fig = px.box(tips, x="time", y="total_bill") +df = px.data.tips() +fig = px.box(df, x="time", y="total_bill") fig.show() ``` @@ -68,8 +66,8 @@ With the `points` argument, display underlying data points with either all point ```python import plotly.express as px -tips = px.data.tips() -fig = px.box(tips, x="time", y="total_bill", points="all") +df = px.data.tips() +fig = px.box(df, x="time", y="total_bill", points="all") fig.show() ``` @@ -79,8 +77,8 @@ For the interpretation of the notches, see https://en.wikipedia.org/wiki/Box_plo ```python import plotly.express as px -tips = px.data.tips() -fig = px.box(tips, x="time", y="total_bill", color="smoker", +df = px.data.tips() +fig = px.box(df, x="time", y="total_bill", color="smoker", notched=True, # used notched shape title="Box plot of total bill", hover_data=["day"] # add day column to hover data @@ -92,7 +90,7 @@ fig.show() If Plotly Express does not provide a good starting point, it is also possible to use the more generic `go.Box` function from `plotly.graph_objects`. All available options for `go.Box` are described in the reference page https://plot.ly/python/reference/#box. -### Basic Box Plot ### +### Basic Box Plot ```python import plotly.graph_objects as go @@ -109,7 +107,7 @@ fig.add_trace(go.Box(y=y1)) fig.show() ``` -### Basic Horizontal Box Plot ### +### Basic Horizontal Box Plot ```python import plotly.graph_objects as go @@ -126,7 +124,7 @@ fig.add_trace(go.Box(x=x1)) fig.show() ``` -### Box Plot That Displays the Underlying Data ### +### Box Plot That Displays the Underlying Data ```python import plotly.graph_objects as go @@ -140,7 +138,7 @@ fig = go.Figure(data=[go.Box(y=[0, 1, 1, 2, 3, 5, 8, 13, 21], fig.show() ``` -### Colored Box Plot ### +### Colored Box Plot ```python import plotly.graph_objects as go @@ -158,7 +156,7 @@ fig.add_trace(go.Box(y=y1, name = 'Sample B', fig.show() ``` -### Box Plot Styling Mean & Standard Deviation ### +### Box Plot Styling Mean & Standard Deviation ```python import plotly.graph_objects as go @@ -180,9 +178,9 @@ fig.add_trace(go.Box( fig.show() ``` -### Styling Outliers ### +### Styling Outliers -The example below shows how to use the `boxpoints` argument. If "outliers", only the sample points lying outside the whiskers are shown. If "suspectedoutliers", the outlier points are shown and points either less than 4Q1-3Q3 or greater than 4Q3-3Q1 are highlighted (using `outliercolor`). If "all", all sample points are shown. If False, only the boxes are shown with no sample points. +The example below shows how to use the `boxpoints` argument. If "outliers", only the sample points lying outside the whiskers are shown. If "suspectedoutliers", the outlier points are shown and points either less than 4Q1-3Q3 or greater than 4Q3-3Q1 are highlighted (using `outliercolor`). If "all", all sample points are shown. If False, only the boxes are shown with no sample points. ```python import plotly.graph_objects as go @@ -236,7 +234,7 @@ fig.update_layout(title_text="Box Plot Styling Outliers") fig.show() ``` -### Grouped Box Plots ### +### Grouped Box Plots ```python import plotly.graph_objects as go @@ -272,7 +270,7 @@ fig.update_layout( fig.show() ``` -### Grouped Horizontal Box Plot ### +### Grouped Horizontal Box Plot ```python import plotly.graph_objects as go @@ -309,7 +307,7 @@ fig.update_traces(orientation='h') # horizontal box plots fig.show() ``` -### Rainbow Box Plots ### +### Rainbow Box Plots ```python import plotly.graph_objects as go @@ -340,8 +338,7 @@ fig.update_layout( fig.show() ``` -### Fully Styled Box Plots ### - +### Fully Styled Box Plots ```python import plotly.graph_objects as go @@ -406,8 +403,6 @@ fig.show() ### Dash Example - - [Dash](https://plot.ly/products/dash/) is an Open Source Python library which can help you convert plotly figures into a reactive, web-based application. Below is a simple example of a dashboard created using Dash. Its [source code](https://github.com/plotly/simple-example-chart-apps/tree/master/dash-boxplot) can easily be deployed to a PaaS. ```python @@ -421,4 +416,5 @@ IFrame(src= "https://dash-simple-apps.plotly.host/dash-boxplot/code", width="100 ``` #### Reference + See https://plot.ly/python/reference/#box for more information and chart attribute options! diff --git a/doc/python/bubble-charts.md b/doc/python/bubble-charts.md index 1abf0b9fb3d..d9df36022db 100644 --- a/doc/python/bubble-charts.md +++ b/doc/python/bubble-charts.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.1 kernelspec: display_name: Python 3 @@ -42,9 +42,9 @@ We first show a bubble chart example using Plotly Express. [Plotly Express](/pyt ```python import plotly.express as px -gapminder = px.data.gapminder() +df = px.data.gapminder() -fig = px.scatter(gapminder.query("year==2007"), x="gdpPercap", y="lifeExp", +fig = px.scatter(df.query("year==2007"), x="gdpPercap", y="lifeExp", size="pop", color="continent", hover_name="country", log_x=True, size_max=60) fig.show() @@ -88,6 +88,7 @@ fig.show() ``` ### Scaling the Size of Bubble Charts + To scale the bubble size, use the attribute `sizeref`. We recommend using the following formula to calculate a `sizeref` value:
`sizeref = 2. * max(array of size values) / (desired maximum marker size ** 2)`
Note that setting 'sizeref' to a value greater than 1, decreases the rendered marker sizes, while setting 'sizeref' to less than 1, increases the rendered marker sizes. See https://plot.ly/python/reference/#scatter-marker-sizeref for more information. @@ -220,4 +221,5 @@ fig.show() ``` ### Reference + See https://plot.ly/python/reference/#scatter for more information and chart attribute options! diff --git a/doc/python/bubble-maps.md b/doc/python/bubble-maps.md index c0f512bc82e..e1abcc7e7b5 100644 --- a/doc/python/bubble-maps.md +++ b/doc/python/bubble-maps.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.1 kernelspec: display_name: Python 3 @@ -35,12 +35,12 @@ jupyter: ### Bubble map with Plotly Express -[Plotly Express](/python/plotly-express/) is the easy-to-use, high-level interface to Plotly, which [operates on "tidy" data](/python/px-arguments/). With ``px.scatter_geo``, each line of the dataframe is represented as a marker point. The column set as the `size` argument gives the size of markers. +[Plotly Express](/python/plotly-express/) is the easy-to-use, high-level interface to Plotly, which [operates on "tidy" data](/python/px-arguments/). With `px.scatter_geo`, each line of the dataframe is represented as a marker point. The column set as the `size` argument gives the size of markers. ```python import plotly.express as px -gapminder = px.data.gapminder().query("year==2007") -fig = px.scatter_geo(gapminder, locations="iso_alpha", color="continent", +df = px.data.gapminder().query("year==2007") +fig = px.scatter_geo(df, locations="iso_alpha", color="continent", hover_name="country", size="pop", projection="natural earth") fig.show() @@ -50,8 +50,8 @@ fig.show() ```python import plotly.express as px -gapminder = px.data.gapminder() -fig = px.scatter_geo(gapminder, locations="iso_alpha", color="continent", +df = px.data.gapminder() +fig = px.scatter_geo(df, locations="iso_alpha", color="continent", hover_name="country", size="pop", animation_frame="year", projection="natural earth") @@ -203,4 +203,5 @@ fig.show() ``` #### Reference + See https://plot.ly/python/reference/#choropleth and https://plot.ly/python/reference/#scattergeo for more information and chart attribute options! diff --git a/doc/python/choropleth-maps.md b/doc/python/choropleth-maps.md index 537b92d5291..654433bb8b4 100644 --- a/doc/python/choropleth-maps.md +++ b/doc/python/choropleth-maps.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.1 kernelspec: display_name: Python 3 @@ -34,8 +34,8 @@ Below we show how to create Choropleth Maps using either Plotly Express' `px.cho ```python import plotly.express as px -gapminder = px.data.gapminder().query("year==2007") -fig = px.choropleth(gapminder, locations="iso_alpha", +df = px.data.gapminder().query("year==2007") +fig = px.choropleth(df, locations="iso_alpha", color="lifeExp", # lifeExp is a column of gapminder hover_name="country", # column to add to hover information color_continuous_scale=px.colors.sequential.Plasma) @@ -239,6 +239,7 @@ fig.show() ``` #### Full County Choropleths + For the full county choropleth doc page checkout https://plot.ly/python/county-choropleth/ ```python @@ -276,7 +277,6 @@ fig.show() ### Dash Example - [Dash](https://plot.ly/products/dash/) is an Open Source Python library which can help you convert plotly figures into a reactive, web-based application. Below is a simple example of a dashboard created using Dash. Its [source code](https://github.com/plotly/simple-example-chart-apps/tree/master/dash-choroplethplot) can easily be deployed to a PaaS. ```python @@ -290,4 +290,5 @@ IFrame(src= "https://dash-simple-apps.plotly.host/dash-choroplethplot/code", wid ``` #### Reference + See https://plot.ly/python/reference/#choropleth for more information and chart attribute options! diff --git a/doc/python/colorscales.md b/doc/python/colorscales.md index ddbff75700b..e5c4795729a 100644 --- a/doc/python/colorscales.md +++ b/doc/python/colorscales.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.2' + format_version: "1.2" jupytext_version: 1.3.0 kernelspec: display_name: Python 3 @@ -22,7 +22,8 @@ jupyter: pygments_lexer: ipython3 version: 3.7.3 plotly: - description: How to set colorscales and heatmap colorscales in Python and Plotly. + description: + How to set colorscales and heatmap colorscales in Python and Plotly. Divergent, sequential, and qualitative colorscales. display_as: file_settings has_thumbnail: true @@ -38,14 +39,15 @@ jupyter: --- ### Predefined colorscales in Plotly Express + A collection of predefined sequential colorscales is provided in the `plotly.express.colors.sequential` module. Here is an example that creates a scatter plot using Plotly Express, with points colored using the Viridis colorscale. ```python import plotly.express as px -iris = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length", +df = px.data.iris() +fig = px.scatter(df, x="sepal_width", y="sepal_length", color="sepal_length", color_continuous_scale=px.colors.sequential.Viridis) fig.show() @@ -55,8 +57,8 @@ It is also possible to specify colorscales by name. Here is an example that spec ```python import plotly.express as px -iris = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length", +df = px.data.iris() +fig = px.scatter(df, x="sepal_width", y="sepal_length", color="sepal_length", color_continuous_scale='Magma') fig.show() @@ -64,12 +66,12 @@ fig.show() ### Reversing a predefined colorscale -You can reverse a predefined colorscale by appending `_r` to its name, for colorscales given either as a string or a `plotly` object. +You can reverse a predefined colorscale by appending `_r` to its name, for colorscales given either as a string or a `plotly` object. ```python import plotly.express as px -iris = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length", +df = px.data.iris() +fig = px.scatter(df, x="sepal_width", y="sepal_length", color="sepal_length", color_continuous_scale='Magma_r') fig.show() @@ -77,7 +79,7 @@ fig.show() ```python import plotly.express as px -data = [[1, .3, .5, .9], +data = [[1, .3, .5, .9], [.3, .1, .4, 1], [.2, .8, .9, .3]] fig = px.imshow(data, color_continuous_scale=px.colors.diverging.Tealrose_r) @@ -219,7 +221,8 @@ fig.show() ``` ### Setting the Midpoint of a Diverging Colorscale -The following example uses [marker.cmid](https://plot.ly/python/reference/#scatter-marker-cmid) attribute to set the mid-point of the color domain by scaling 'cmin' and/or 'cmax' to be equidistant to this point. It only has impact when [marker.color](https://plot.ly/python/reference/#scattercarpet-marker-line-color) sets to a numerical array, and 'marker.cauto' is `True`. + +The following example uses [marker.cmid](https://plot.ly/python/reference/#scatter-marker-cmid) attribute to set the mid-point of the color domain by scaling 'cmin' and/or 'cmax' to be equidistant to this point. It only has impact when [marker.color](https://plot.ly/python/reference/#scattercarpet-marker-line-color) sets to a numerical array, and 'marker.cauto' is `True`. ```python import plotly.graph_objects as go @@ -241,7 +244,7 @@ import plotly.graph_objects as go a = list(range(-10,5)) b = list(range(-5,10)) c = list(range(-5,15)) - + fig = go.Figure(go.Heatmap( z=[a, b, c], colorscale='RdBu', @@ -308,6 +311,7 @@ fig.show() ``` ### Share Color Axis + This example shows how traces can share colorbars. To share colorscale information in multiple subplots, you can use [coloraxis](https://plot.ly/javascript/reference/#scatter-marker-line-coloraxis). ```python @@ -326,7 +330,6 @@ fig.update_layout(coloraxis = {'colorscale':'viridis'}) fig.show() ``` - ### Logarithmic Colorscale ```python diff --git a/doc/python/creating-and-updating-figures.md b/doc/python/creating-and-updating-figures.md index c19876cafbe..89710a448a9 100644 --- a/doc/python/creating-and-updating-figures.md +++ b/doc/python/creating-and-updating-figures.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.1 kernelspec: display_name: Python 3 @@ -30,8 +30,8 @@ jupyter: page_type: example_index permalink: python/creating-and-updating-figures/ redirect_from: - - python/user-guide/ - - python/user-g/ + - python/user-guide/ + - python/user-g/ thumbnail: thumbnail/creating-and-updating-figures.png v4upgrade: true order: 2 @@ -40,6 +40,7 @@ jupyter: ### Representing Figures #### Figures as dictionaries + The goal of plotly.py is to provide a pleasant Python interface for creating figure specifications for display in the Plotly.js JavaScript library. In Plotly.js, a figure is specified by a declarative JSON data structure, and so the ultimate responsibility of plotly.py is to produce Python dictionaries that can be serialized into a JSON data structure that represents a valid figure. As a concrete example, here is a Python dictionary that represents a figure containing a single bar trace and a title. @@ -57,24 +58,24 @@ import plotly.io as pio pio.show(fig) ``` -The value of the top-level `"data"` key is a list of trace specifications. Each trace specification has a special `"type"` key that indicates the trace type that is being defined (e.g. a `"bar"`, `"scatter"`, `"contour"`, etc.). The rest of the keys in the trace specification are used to configure the properties of the trace of this type. - -The value of the top-level `"layout"` key is a dictionary that specifies the properties of the figure's layout. In contrast to trace configuration options that apply to individual traces, the layout configuration options apply to the figure as a whole, customizing items like the axes, annotations, shapes, legend, and more. +The value of the top-level `"data"` key is a list of trace specifications. Each trace specification has a special `"type"` key that indicates the trace type that is being defined (e.g. a `"bar"`, `"scatter"`, `"contour"`, etc.). The rest of the keys in the trace specification are used to configure the properties of the trace of this type. -The [*Full Reference*](https://plot.ly/python/reference/) page contains descriptions of all of the supported trace and layout options. +The value of the top-level `"layout"` key is a dictionary that specifies the properties of the figure's layout. In contrast to trace configuration options that apply to individual traces, the layout configuration options apply to the figure as a whole, customizing items like the axes, annotations, shapes, legend, and more. -If working from the *Full Reference* to build figures as Python dictionaries and lists suites your needs, go for it! This is a perfectly valid way to use plotly.py to build figures. On the other hand, if you would like an API that offers a bit more assistance, read on to learn about graph objects. +The [_Full Reference_](https://plot.ly/python/reference/) page contains descriptions of all of the supported trace and layout options. +If working from the _Full Reference_ to build figures as Python dictionaries and lists suites your needs, go for it! This is a perfectly valid way to use plotly.py to build figures. On the other hand, if you would like an API that offers a bit more assistance, read on to learn about graph objects. #### Figures as graph objects + As an alternative to working with Python dictionaries, plotly.py provides a hierarchy of classes called "graph objects" that may be used to construct figures. Graph objects have several benefits compared to plain dictionaries. - 1. Graph objects provide precise data validation. So if you provide an invalid property name or an invalid property value, an exception will be raised with a helpful error message describing the problem. - 2. Graph objects contain descriptions of each property as Python docstrings. You can use these docstrings to learn about the available properties as an alternative to consulting the *Full Reference*. - 3. Properties of graph objects can be accessed using dictionary-style key lookup (e.g. `fig["layout"]`) or class-style property access (e.g. `fig.layout`). - 4. Graph objects support higher-level convenience functions for making updates to already constructed figures, as described below. +1. Graph objects provide precise data validation. So if you provide an invalid property name or an invalid property value, an exception will be raised with a helpful error message describing the problem. +2. Graph objects contain descriptions of each property as Python docstrings. You can use these docstrings to learn about the available properties as an alternative to consulting the _Full Reference_. +3. Properties of graph objects can be accessed using dictionary-style key lookup (e.g. `fig["layout"]`) or class-style property access (e.g. `fig.layout`). +4. Graph objects support higher-level convenience functions for making updates to already constructed figures, as described below. -Graph objects are stored in a hierarchy of modules under the `plotly.graph_objects` package. Here is an example of one way that the figure above could be constructed using graph objects. +Graph objects are stored in a hierarchy of modules under the `plotly.graph_objects` package. Here is an example of one way that the figure above could be constructed using graph objects. ```python import plotly.graph_objects as go @@ -100,14 +101,15 @@ fig = go.Figure({ fig.show() ``` -Once you have a figure as a graph object, you can retrieve the dictionary representation using the `fig.to_dict()` method. You can also retrieve the JSON string representation using the `fig.to_json()` method. - +Once you have a figure as a graph object, you can retrieve the dictionary representation using the `fig.to_dict()` method. You can also retrieve the JSON string representation using the `fig.to_json()` method. ### Creating figures + This section summarizes several ways to create new graph object figures with plotly.py #### Constructor -As demonstrated above, you can build a complete figure by passing trace and layout specifications to the `plotly.graph_objects.Figure` constructor. These trace and layout specifications can be either dictionaries or graph objects. Here, for example, the traces are specified using graph objects and the layout is specified as a dictionary. + +As demonstrated above, you can build a complete figure by passing trace and layout specifications to the `plotly.graph_objects.Figure` constructor. These trace and layout specifications can be either dictionaries or graph objects. Here, for example, the traces are specified using graph objects and the layout is specified as a dictionary. ```python import plotly.graph_objects as go @@ -119,12 +121,13 @@ fig.show() ``` #### Plotly express + Plotly express (included as the `plotly.express` module) is a high-level data exploration API that produces graph object figures. ```python import plotly.express as px -iris = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length", color="species") +df = px.data.iris() +fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species") # If you print fig, you'll see that it's just a regular figure with data and layout # print(fig) @@ -133,7 +136,8 @@ fig.show() ``` #### Figure factories -Figure factories (included in plotly.py in the `plotly.figure_factory` module) are functions that produce graph object figures, often to satisfy the needs of specialized domains. Here's an example of using the `create_quiver` figure factory to construct a graph object figure that displays a 2D quiver plot. + +Figure factories (included in plotly.py in the `plotly.figure_factory` module) are functions that produce graph object figures, often to satisfy the needs of specialized domains. Here's an example of using the `create_quiver` figure factory to construct a graph object figure that displays a 2D quiver plot. ```python import numpy as np @@ -147,7 +151,8 @@ fig.show() ``` #### Make subplots -The `plotly.subplots.make_subplots` function produces a graph object figure that is preconfigured with a grid of subplots that traces can be added to. The `add_trace` function will be discussed more below. + +The `plotly.subplots.make_subplots` function produces a graph object figure that is preconfigured with a grid of subplots that traces can be added to. The `add_trace` function will be discussed more below. ```python from plotly.subplots import make_subplots @@ -158,10 +163,12 @@ fig.show() ``` ### Updating figures + Regardless of how a graph object figure was constructed, it can be updated by adding additional traces and modifying its properties. #### Adding traces -New traces can be added to a graph object figure using the `add_trace` method. This method accepts a graph object trace (an instance of `go.Scatter`, `go.Bar`, etc.) and adds it to the figure. This allows you to start with an empty figure, and add traces to it sequentially. + +New traces can be added to a graph object figure using the `add_trace` method. This method accepts a graph object trace (an instance of `go.Scatter`, `go.Bar`, etc.) and adds it to the figure. This allows you to start with an empty figure, and add traces to it sequentially. ```python import plotly.graph_objects as go @@ -174,8 +181,8 @@ You can also add traces to a figure produced by a figure factory or Plotly Expre ```python import plotly.express as px -iris = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length", color="species") +df = px.data.iris() +fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species") fig.add_trace( go.Scatter( x=[2, 4], @@ -188,6 +195,7 @@ fig.show() ``` #### Adding traces to subplots + If a figure was created using `plotly.subplots.make_subplots`, then the `row` and `col` argument to `add_trace` can be used to add a trace to a particular subplot. ```python @@ -202,8 +210,8 @@ This also works for figures created by Plotly Express using the `facet_row` and ```python import plotly.express as px -iris = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length", color="species", facet_col="species") +df = px.data.iris() +fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", facet_col="species") reference_line = go.Scatter(x=[2, 4], y=[4, 8], mode="lines", @@ -216,6 +224,7 @@ fig.show() ``` #### Add trace convenience methods + As an alternative to the `add_trace` method, graph object figures have a family of methods of the form `add_{trace}`, where `{trace}` is the name of a trace type, for constructing and adding traces of each trace type. Here is the previous subplot example, adapted to add the scatter trace using `fig.add_scatter` and to add the bar trace using `fig.add_bar`. ```python @@ -227,9 +236,10 @@ fig.show() ``` #### Magic underscore notation + To make it easier to work with nested properties graph object constructors, and many graph object methods, support magic underscore notation. This allows you to reference nested properties by joining together multiple nested property names with underscores. -For example, specifying the figure title in the figure constructor *without* magic underscore notation requires setting the `layout` argument to `dict(title=dict(text="A Chart"))`. Similarly, setting the line color of a scatter trace requires setting the `marker` property to `dict(color="crimson")`. +For example, specifying the figure title in the figure constructor _without_ magic underscore notation requires setting the `layout` argument to `dict(title=dict(text="A Chart"))`. Similarly, setting the line color of a scatter trace requires setting the `marker` property to `dict(color="crimson")`. ```python import plotly.graph_objects as go @@ -253,10 +263,11 @@ fig.show() Magic underscore notation is supported throughout the graph objects API, and it can often significantly simplify operations involving deeply nested properties. -> Note: When you see keyword arguments with underscores passed to a graph object constructor or method, it is almost always safe to assume that it is an application of magic underscore notation. We have to say "almost always" rather than "always" because there are a few property names in the plotly schema that contain underscores: error_x, error_y, error_z, copy_xstyle, copy_ystyle, copy_zstyle, paper_bgcolor, and plot_bgcolor. These were added back in the early days of the library (2012-2013) before we standardized on banning underscores from property names. +> Note: When you see keyword arguments with underscores passed to a graph object constructor or method, it is almost always safe to assume that it is an application of magic underscore notation. We have to say "almost always" rather than "always" because there are a few property names in the plotly schema that contain underscores: error_x, error_y, error_z, copy_xstyle, copy_ystyle, copy_zstyle, paper_bgcolor, and plot_bgcolor. These were added back in the early days of the library (2012-2013) before we standardized on banning underscores from property names. #### The update layout method -Graph object figures support an `update_layout` method that may be used to update multiple nested properties of a figure's layout. Here is an example of updating the text and font size of a figure's title using `update_layout`. + +Graph object figures support an `update_layout` method that may be used to update multiple nested properties of a figure's layout. Here is an example of updating the text and font size of a figure's title using `update_layout`. ```python import plotly.graph_objects as go @@ -287,9 +298,9 @@ fig.update_layout( font=go.layout.title.Font(size=30))); ``` - #### The update traces method -Graph object figures support an `update_traces` method that may be used to update multiple nested properties of one or more of a figure's traces. To show some examples, we will start with a figure that contains bar and scatter traces across two subplots. + +Graph object figures support an `update_traces` method that may be used to update multiple nested properties of one or more of a figure's traces. To show some examples, we will start with a figure that contains bar and scatter traces across two subplots. ```python from plotly.subplots import make_subplots @@ -341,7 +352,7 @@ fig.update_traces(marker=dict(color="RoyalBlue")) fig.show() ``` -The `update_traces` method supports a `selector` argument to control which traces should be updated. Only traces with properties that match the selector will be updated. Here is an example of using a selector to only update the color of the `bar` traces +The `update_traces` method supports a `selector` argument to control which traces should be updated. Only traces with properties that match the selector will be updated. Here is an example of using a selector to only update the color of the `bar` traces ```python from plotly.subplots import make_subplots @@ -369,7 +380,7 @@ fig.update_traces(marker=dict(color="RoyalBlue"), fig.show() ``` -Magic underscore notation can be used in the selector to match nested properties. Here is an example of updating the color of all traces that were formally colored `"MediumPurple"`. +Magic underscore notation can be used in the selector to match nested properties. Here is an example of updating the color of all traces that were formally colored `"MediumPurple"`. ```python from plotly.subplots import make_subplots @@ -397,7 +408,7 @@ fig.update_traces(marker_color="RoyalBlue", fig.show() ``` -For figures with subplots, the `update_traces` method also supports `row` and `col` arguments to control which traces should be updated. Only traces in the specified subplot row and column will be updated. Here is an example of updating the color of all traces in the second subplot column +For figures with subplots, the `update_traces` method also supports `row` and `col` arguments to control which traces should be updated. Only traces in the specified subplot row and column will be updated. Here is an example of updating the color of all traces in the second subplot column ```python from plotly.subplots import make_subplots @@ -430,8 +441,8 @@ The `update_traces` method can also be used on figures produced by figure factor ```python import pandas as pd import plotly.express as px -iris = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length", color="species", facet_col="species", trendline="ols") +df = px.data.iris() +fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", facet_col="species", trendline="ols") fig.update_traces( line=dict(dash="dot", width=4), selector=dict(type="scatter", mode="lines")) @@ -440,13 +451,13 @@ fig.show() ### Overwrite existing properties when using update methods -`update_layout` and `update_traces` have an `overwrite` keyword argument, defaulting to False, in which case updates are applied recursively to the *existing* nested property structure. When set to True, the prior value of existing properties is overwritten with the provided value. +`update_layout` and `update_traces` have an `overwrite` keyword argument, defaulting to False, in which case updates are applied recursively to the _existing_ nested property structure. When set to True, the prior value of existing properties is overwritten with the provided value. -In the example below, the red color of markers is overwritten when updating `marker` in `update_traces` with `overwrite=True`. Note that setting instead `marker_opacity` with the magic underscore would not overwrite `marker_color` because properties would be overwritten starting only at the level of `marker.opacity`. +In the example below, the red color of markers is overwritten when updating `marker` in `update_traces` with `overwrite=True`. Note that setting instead `marker_opacity` with the magic underscore would not overwrite `marker_color` because properties would be overwritten starting only at the level of `marker.opacity`. ```python import plotly.graph_objects as go -fig = go.Figure(go.Bar(x=[1, 2, 3], y=[6, 4, 9], +fig = go.Figure(go.Bar(x=[1, 2, 3], y=[6, 4, 9], marker_color="red")) # will be overwritten below fig.update_traces( overwrite=True, @@ -456,17 +467,18 @@ fig.show() ``` #### The for each trace method -Suppose the updates that you want to make to a collection of traces depend on the current values of certain trace properties. The `update_traces` method cannot handle this situation, but the `for_each_trace` method can. -As its first argument, the `for_each_trace` method accepts a function that accepts and updates one trace at a time. Like `update_traces`, `for_each_trace` also accepts `selector`, `row`, and `col` arguments to control which traces should be considered. +Suppose the updates that you want to make to a collection of traces depend on the current values of certain trace properties. The `update_traces` method cannot handle this situation, but the `for_each_trace` method can. + +As its first argument, the `for_each_trace` method accepts a function that accepts and updates one trace at a time. Like `update_traces`, `for_each_trace` also accepts `selector`, `row`, and `col` arguments to control which traces should be considered. Here is an example of using `for_each_trace` to replace the equal-sign with a colon in the legend name of each trace in a figure produced by Plotly Express. ```python import pandas as pd import plotly.express as px -iris = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length", color="species") +df = px.data.iris() +fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species") fig.for_each_trace( lambda trace: trace.update(name=trace.name.replace("=", ": ")), @@ -476,13 +488,14 @@ fig.show() ``` #### The update axis methods -Graph object figures support `update_xaxes` and `update_yaxes` methods that may be used to update multiple nested properties of one or more of a figure's axes. Here is an example of using `update_xaxes` to disable the vertical grid lines across all subplots in a figure produced by Plotly Express. + +Graph object figures support `update_xaxes` and `update_yaxes` methods that may be used to update multiple nested properties of one or more of a figure's axes. Here is an example of using `update_xaxes` to disable the vertical grid lines across all subplots in a figure produced by Plotly Express. ```python import pandas as pd import plotly.express as px -iris = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length", color="species", facet_col="species") +df = px.data.iris() +fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", facet_col="species") fig.update_xaxes(showgrid=False) fig.show() ``` @@ -493,16 +506,16 @@ There are also `for_each_xaxis` and `for_each_yaxis` methods that are analogous `go` figures also support `update_layout_images` in order to [update background layout images](/python/images/), `update_annotations` in order to [update annotations](/python/text-and-annotations/#multiple-annotations), and `update-shapes` in order to [update shapes](/python/shapes/). - #### Chaining figure operations -All of the figure update operations described above are methods that return a reference to the figure being modified. This makes it possible the chain multiple figure modification operations together into a single expression. + +All of the figure update operations described above are methods that return a reference to the figure being modified. This makes it possible the chain multiple figure modification operations together into a single expression. Here is an example of a chained expression that creates a faceted scatter plot with OLS trend lines using Plotly Express, sets the title font size using `update_layout`, disables vertical grid lines using `update_xaxes`, updates the width and dash pattern of the trend lines using `update_traces`, and then displays the figure using `show`. ```python import plotly.express as px -iris = px.data.iris() -(px.scatter(iris, x="sepal_width", y="sepal_length", color="species", +df = px.data.iris() +(px.scatter(df, x="sepal_width", y="sepal_length", color="species", facet_col="species", trendline="ols", title="Iris Dataset") .update_layout(title_font_size=24) .update_xaxes(showgrid=False) @@ -513,7 +526,8 @@ iris = px.data.iris() ``` #### Property assignment -Trace and layout properties can be updated using property assignment syntax. Here is an example of setting the figure title using property assignment. + +Trace and layout properties can be updated using property assignment syntax. Here is an example of setting the figure title using property assignment. ```python import plotly.graph_objects as go diff --git a/doc/python/distplot.md b/doc/python/distplot.md index 23e5fbcb335..bf1987a77c9 100644 --- a/doc/python/distplot.md +++ b/doc/python/distplot.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.1 kernelspec: display_name: Python 3 @@ -41,18 +41,18 @@ For example, the `plotly.express` function `px.histogram` can add a subplot with ```python import plotly.express as px -tips = px.data.tips() -fig = px.histogram(tips, x="total_bill", y="tip", color="sex", marginal="rug", - hover_data=tips.columns) +df = px.data.tips() +fig = px.histogram(df, x="total_bill", y="tip", color="sex", marginal="rug", + hover_data=df.columns) fig.show() ``` ```python import plotly.express as px -tips = px.data.tips() -fig = px.histogram(tips, x="total_bill", y="tip", color="sex", +df = px.data.tips() +fig = px.histogram(df, x="total_bill", y="tip", color="sex", marginal="box", # or violin, rug - hover_data=tips.columns) + hover_data=df.columns) fig.show() ``` @@ -60,7 +60,6 @@ fig.show() The distplot figure factory displays a combination of statistical representations of numerical data, such as histogram, kernel density estimation or normal curve, and rug plot. - #### Basic Distplot A histogram, a kde plot and a rug plot are displayed. diff --git a/doc/python/error-bars.md b/doc/python/error-bars.md index 801923a8762..e4870b7a223 100644 --- a/doc/python/error-bars.md +++ b/doc/python/error-bars.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.2.0 kernelspec: display_name: Python 3 @@ -39,9 +39,9 @@ jupyter: ```python import plotly.express as px -iris = px.data.iris() -iris["e"] = iris["sepal_width"]/100 -fig = px.scatter(iris, x="sepal_width", y="sepal_length", color="species", +df = px.data.iris() +df["e"] = df["sepal_width"]/100 +fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", error_x="e", error_y="e") fig.show() ``` @@ -50,10 +50,10 @@ fig.show() ```python import plotly.express as px -iris = px.data.iris() -iris["e_plus"] = iris["sepal_width"]/100 -iris["e_minus"] = iris["sepal_width"]/40 -fig = px.scatter(iris, x="sepal_width", y="sepal_length", color="species", +df = px.data.iris() +df["e_plus"] = df["sepal_width"]/100 +df["e_minus"] = df["sepal_width"]/40 +fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", error_y="e_plus", error_y_minus="e_minus") fig.show() ``` @@ -201,4 +201,5 @@ fig.show() ``` #### Reference + See https://plot.ly/python/reference/#scatter for more information and chart attribute options! diff --git a/doc/python/facet-plots.md b/doc/python/facet-plots.md index f34008df9b1..330fb749639 100644 --- a/doc/python/facet-plots.md +++ b/doc/python/facet-plots.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.1 kernelspec: display_name: Python 3 @@ -30,13 +30,12 @@ jupyter: order: 8 page_type: u-guide permalink: python/facet-plots/ - redirect_from: + redirect_from: - python/trellis-plots/ - python/facet-trellis/ thumbnail: thumbnail/facet-trellis-thumbnail.jpg --- - ### Facet and Trellis Plots Facet plots, also known as trellis plots or small multiples, are figures made up of multiple subplots which have the same set of axes, where each subplot shows a subset of the data. While it is straightforward to use `plotly`'s @@ -46,8 +45,8 @@ Facet plots, also known as trellis plots or small multiples, are figures made up ```python import plotly.express as px -tips = px.data.tips() -fig = px.scatter(tips, x="total_bill", y="tip", color="smoker", facet_col="sex") +df = px.data.tips() +fig = px.scatter(df, x="total_bill", y="tip", color="smoker", facet_col="sex") fig.show() ``` @@ -55,14 +54,14 @@ fig.show() ```python import plotly.express as px -tips = px.data.tips() -fig = px.bar(tips, x="size", y="total_bill", color="sex", facet_row="smoker") +df = px.data.tips() +fig = px.bar(df, x="size", y="total_bill", color="sex", facet_row="smoker") fig.show() ``` ### Wrapping Column Facets -When the facet dimension has a large number of unique values, it is possible to wrap columns using the `facet_col_wrap` argument. +When the facet dimension has a large number of unique values, it is possible to wrap columns using the `facet_col_wrap` argument. ```python import plotly.express as px @@ -76,15 +75,15 @@ fig.show() ```python import plotly.express as px -tips = px.data.tips() -fig = px.histogram(tips, x="total_bill", y="tip", color="sex", facet_row="time", facet_col="day", +df = px.data.tips() +fig = px.histogram(df, x="total_bill", y="tip", color="sex", facet_row="time", facet_col="day", category_orders={"day": ["Thur", "Fri", "Sat", "Sun"], "time": ["Lunch", "Dinner"]}) fig.show() ``` ### Facets with independent axes -By default, facet axes are linked together: zooming inside one of the facets will also zoom in the other facets. You can disable this behaviour when you use `facet_row` only, by disabling `matches` on the Y axes, or when using `facet_col` only, by disabling `matches` on the X axes. It is not recommended to use this approach when using `facet_row` and `facet_col` together, as in this case it becomes very hard to understand the labelling of axes and grid lines. +By default, facet axes are linked together: zooming inside one of the facets will also zoom in the other facets. You can disable this behaviour when you use `facet_row` only, by disabling `matches` on the Y axes, or when using `facet_col` only, by disabling `matches` on the X axes. It is not recommended to use this approach when using `facet_row` and `facet_col` together, as in this case it becomes very hard to understand the labelling of axes and grid lines. ```python import plotly.express as px diff --git a/doc/python/filled-area-plots.md b/doc/python/filled-area-plots.md index 3cae87e72d1..b32c7915110 100644 --- a/doc/python/filled-area-plots.md +++ b/doc/python/filled-area-plots.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.1 kernelspec: display_name: Python 3 @@ -35,7 +35,6 @@ jupyter: This example shows how to fill the area enclosed by traces. - ## Filled area plot with plotly.express [Plotly Express](/python/plotly-express/) is the easy-to-use, high-level interface to Plotly, which [operates on "tidy" data](/python/px-arguments/). @@ -44,8 +43,8 @@ This example shows how to fill the area enclosed by traces. ```python import plotly.express as px -gapminder = px.data.gapminder() -fig = px.area(gapminder, x="year", y="pop", color="continent", +df = px.data.gapminder() +fig = px.area(df, x="year", y="pop", color="continent", line_group="country") fig.show() ``` @@ -210,6 +209,7 @@ fig.show() ``` #### Reference + See https://plot.ly/python/reference/#scatter-line and https://plot.ly/python/reference/#scatter-fill for more information and attribute options! diff --git a/doc/python/histograms.md b/doc/python/histograms.md index 6f9a452983f..18aac94dbe4 100644 --- a/doc/python/histograms.md +++ b/doc/python/histograms.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.1 kernelspec: display_name: Python 3 @@ -41,21 +41,20 @@ bar, go to the [Bar Chart tutorial](/python/bar-charts/). ## Histogram with Plotly Express - [Plotly Express](/python/plotly-express/) is the easy-to-use, high-level interface to Plotly, which [operates on "tidy" data](/python/px-arguments/). ```python import plotly.express as px -tips = px.data.tips() -fig = px.histogram(tips, x="total_bill") +df = px.data.tips() +fig = px.histogram(df, x="total_bill") fig.show() ``` ```python import plotly.express as px -tips = px.data.tips() +df = px.data.tips() # Here we use a column with categorical data -fig = px.histogram(tips, x="day") +fig = px.histogram(df, x="day") fig.show() ``` @@ -65,8 +64,8 @@ By default, the number of bins is chosen so that this number is comparable to th ```python import plotly.express as px -tips = px.data.tips() -fig = px.histogram(tips, x="total_bill", nbins=20) +df = px.data.tips() +fig = px.histogram(df, x="total_bill", nbins=20) fig.show() ``` @@ -76,8 +75,8 @@ The default mode is to represent the count of samples in each bin. With the `his ```python import plotly.express as px -tips = px.data.tips() -fig = px.histogram(tips, x="total_bill", histnorm='probability density') +df = px.data.tips() +fig = px.histogram(df, x="total_bill", histnorm='probability density') fig.show() ``` @@ -85,8 +84,8 @@ fig.show() ```python import plotly.express as px -tips = px.data.tips() -fig = px.histogram(tips, x="total_bill", +df = px.data.tips() +fig = px.histogram(df, x="total_bill", title='Histogram of bills', labels={'total_bill':'total bill'}, # can specify one label per df column opacity=0.8, @@ -100,8 +99,8 @@ fig.show() ```python import plotly.express as px -tips = px.data.tips() -fig = px.histogram(tips, x="total_bill", color="sex") +df = px.data.tips() +fig = px.histogram(df, x="total_bill", color="sex") fig.show() ``` @@ -111,8 +110,8 @@ For each bin of `x`, one can compute a function of data using `histfunc`. The ar ```python import plotly.express as px -tips = px.data.tips() -fig = px.histogram(tips, x="total_bill", y="tip", histfunc='avg') +df = px.data.tips() +fig = px.histogram(df, x="total_bill", y="tip", histfunc='avg') fig.show() ``` @@ -122,9 +121,9 @@ With the `marginal` keyword, a subplot is drawn alongside the histogram, visuali ```python import plotly.express as px -tips = px.data.tips() -fig = px.histogram(tips, x="total_bill", color="sex", marginal="rug", # can be `box`, `violin` - hover_data=tips.columns) +df = px.data.tips() +fig = px.histogram(df, x="total_bill", color="sex", marginal="rug", # can be `box`, `violin` + hover_data=df.columns) fig.show() ``` @@ -132,7 +131,7 @@ fig.show() If Plotly Express does not provide a good starting point, it is also possible to use the more generic `go.Histogram` from `plotly.graph_objects`. All of the available histogram options are described in the histogram section of the reference page: https://plot.ly/python/reference#histogram. -### Basic Histogram ### +### Basic Histogram ```python import plotly.graph_objects as go @@ -159,7 +158,7 @@ fig = go.Figure(data=[go.Histogram(x=x, histnorm='probability')]) fig.show() ``` -### Horizontal Histogram ### +### Horizontal Histogram ```python import plotly.graph_objects as go @@ -173,7 +172,7 @@ fig = go.Figure(data=[go.Histogram(y=y)]) fig.show() ``` -### Overlaid Histogram ### +### Overlaid Histogram ```python import plotly.graph_objects as go @@ -289,6 +288,7 @@ fig.show() ``` ### Custom Binning + For custom binning along x-axis, use the attribute [`nbinsx`](https://plot.ly/python/reference/#histogram-nbinsx). Please note that the autobin algorithm will choose a 'nice' round bin size that may result in somewhat fewer than `nbinsx` total bins. Alternatively, you can set the exact values for [`xbins`](https://plot.ly/python/reference/#histogram-xbins) along with `autobinx = False`. ```python @@ -341,16 +341,17 @@ If you want to display information about the individual items within each histog ```python import plotly.express as px -tips = px.data.tips() -fig1 = px.bar(tips, x='day', y='tip', height=300, +df = px.data.tips() +fig1 = px.bar(df, x='day', y='tip', height=300, title='Stacked Bar Chart - Hover on individual items') -fig2 = px.histogram(tips, x='day', y='tip', histfunc='sum', height=300, +fig2 = px.histogram(df, x='day', y='tip', histfunc='sum', height=300, title='Histogram Chart') fig1.show() fig2.show() ``` ### Share bins between histograms + In this example both histograms have a compatible bin settings using [bingroup](https://plot.ly/python/reference/#histogram-bingroup) attribute. Note that traces on the same subplot, and with the same `barmode` ("stack", "relative", "group") are forced into the same `bingroup`, however traces with `barmode = "overlay"` and on different axes (of the same axis type) can have compatible bin settings. Histogram and [histogram2d](https://plot.ly/python/2D-Histogram/) trace can share the same `bingroup`. ```python @@ -374,7 +375,6 @@ fig.show() ### Dash Example - [Dash](https://plot.ly/products/dash/) is an Open Source Python library which can help you convert plotly figures into a reactive, web-based application. Below is a simple example of a dashboard created using Dash. Its [source code](https://github.com/plotly/simple-example-chart-apps/tree/master/dash-histogramplot) can easily be deployed to a PaaS. ```python @@ -390,4 +390,5 @@ IFrame(src= "https://dash-simple-apps.plotly.host/dash-histogramplot/code", widt ``` #### Reference + See https://plot.ly/python/reference/#histogram for more information and chart attribute options! diff --git a/doc/python/horizontal-bar-charts.md b/doc/python/horizontal-bar-charts.md index ef46398c0f3..c5e9de9b188 100644 --- a/doc/python/horizontal-bar-charts.md +++ b/doc/python/horizontal-bar-charts.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.1 kernelspec: display_name: Python 3 @@ -35,19 +35,16 @@ jupyter: See more examples of bar charts (including vertical bar charts) and styling options [here](https://plot.ly/python/bar-charts/). - ### Horizontal Bar Chart with Plotly Express [Plotly Express](/python/plotly-express/) is the easy-to-use, high-level interface to Plotly, which [operates on "tidy" data](/python/px-arguments/). For a horizontal bar char, use the `px.bar` function with `orientation='h'`. - #### Basic Horizontal Bar Chart with Plotly Express - ```python import plotly.express as px -tips = px.data.tips() -fig = px.bar(tips, x="total_bill", y="day", orientation='h') +df = px.data.tips() +fig = px.bar(df, x="total_bill", y="day", orientation='h') fig.show() ``` @@ -57,8 +54,8 @@ In this example a column is used to color the bars, and we add the information f ```python import plotly.express as px -tips = px.data.tips() -fig = px.bar(tips, x="total_bill", y="sex", color='day', orientation='h', +df = px.data.tips() +fig = px.bar(df, x="total_bill", y="sex", color='day', orientation='h', hover_data=["tip", "size"], height=400, title='Restaurant bills') @@ -69,7 +66,6 @@ fig.show() When data are not available as a tidy dataframe, you can use the more generic function `go.Bar` from `plotly.graph_objects`. All the options of `go.Bar` are documented in the reference https://plot.ly/python/reference/#bar - #### Basic Horizontal Bar Chart ```python @@ -338,4 +334,5 @@ fig.show() ``` ### Reference + See more examples of bar charts and styling options [here](https://plot.ly/python/bar-charts/).
See https://plot.ly/python/reference/#bar for more information and chart attribute options! diff --git a/doc/python/hover-text-and-formatting.md b/doc/python/hover-text-and-formatting.md index 0de4eac12a9..585a61f746b 100644 --- a/doc/python/hover-text-and-formatting.md +++ b/doc/python/hover-text-and-formatting.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.2' + format_version: "1.2" jupytext_version: 1.3.0 kernelspec: display_name: Python 3 @@ -33,6 +33,7 @@ jupyter: --- #### Hover text with Plotly Express + Many Plotly Express functions support configurable hover text. The `hover_data` argument accepts a list of column names to be added to the hover tooltip. The `hover_name` property controls which column is displayed in bold as the tooltip title. Here is an example that creates a scatter plot using Plotly Express with custom hover data and a custom hover name. @@ -40,9 +41,9 @@ Here is an example that creates a scatter plot using Plotly Express with custom ```python import plotly.express as px -gapminder_2007 = px.data.gapminder().query("year==2007") +df_2007 = px.data.gapminder().query("year==2007") -fig = px.scatter(gapminder_2007, x="gdpPercap", y="lifeExp", log_x=True, +fig = px.scatter(df_2007, x="gdpPercap", y="lifeExp", log_x=True, hover_name="country", hover_data=["continent"]) fig.show() @@ -105,7 +106,7 @@ fig.show() To customize the tooltip on your graph you can use [hovertemplate](https://plot.ly/python/reference/#pie-hovertemplate), which is a template string used for rendering the information that appear on hoverbox. This template string can include `variables` in %{variable} format, `numbers` in [d3-format's syntax](https://github.com/d3/d3-3.x-api-reference/blob/master/Formatting.md#d3_forma), and `date` in [d3-time-format's syntax](https://github.com/d3/d3-3.x-api-reference/blob/master/Time-Formatting.md#format). Hovertemplate customize the tooltip text vs. [texttemplate](https://plot.ly/python/reference/#pie-texttemplate) which customizes the text that appears on your chart.
-Set the horizontal alignment of the text within tooltip with [hoverlabel.align](https://plot.ly/python/reference/#layout-hoverlabel-align). +Set the horizontal alignment of the text within tooltip with [hoverlabel.align](https://plot.ly/python/reference/#layout-hoverlabel-align). ```python import plotly.graph_objects as go @@ -127,7 +128,7 @@ fig.add_trace(go.Scatter( showlegend = False)) fig.update_layout( - hoverlabel_align = 'right', + hoverlabel_align = 'right', title = "Set hover text with hovertemplate") fig.show() @@ -148,6 +149,7 @@ fig.show() ``` ### Advanced Hover Template + The following example shows how to format hover template. [Here](https://plot.ly/python/v3/hover-text-and-formatting/#dash-example) is an example to see how to format hovertemplate in Dash. ```python @@ -214,13 +216,13 @@ z1, z2, z3 = np.random.random((3, 7, 7)) customdata = np.dstack((z2, z3)) fig = make_subplots(1, 2, subplot_titles=['z1', 'z2']) fig.add_trace(go.Heatmap( - z=z1, + z=z1, customdata=np.dstack((z2, z3)), hovertemplate='z1:%{z:.3f}
z2:%{customdata[0]:.3f}
z3: %{customdata[1]:.3f} ', coloraxis="coloraxis1", name=''), 1, 1) fig.add_trace(go.Heatmap( - z=z2, + z=z2, customdata=np.dstack((z1, z3)), hovertemplate='z1:%{customdata[0]:.3f}
z2:%{z:.3f}
z3: %{customdata[1]:.3f} ', coloraxis="coloraxis1", name=''), @@ -230,6 +232,7 @@ fig.show() ``` ### Set Hover Template in Mapbox + ```python import plotly.graph_objects as go @@ -256,4 +259,5 @@ fig.show() ``` #### Reference + See https://plot.ly/python/reference/ for more information and chart attribute options! diff --git a/doc/python/line-and-scatter.md b/doc/python/line-and-scatter.md index 37c6ecf3e74..b459f9dd99c 100644 --- a/doc/python/line-and-scatter.md +++ b/doc/python/line-and-scatter.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.1 kernelspec: display_name: Python 3 @@ -38,7 +38,7 @@ jupyter: [Plotly Express](/python/plotly-express/) is the easy-to-use, high-level interface to Plotly, which [operates on "tidy" data](/python/px-arguments/). -With ``px.scatter``, each data point is represented as a marker point, which location is given by the `x` and `y` columns. +With `px.scatter`, each data point is represented as a marker point, which location is given by the `x` and `y` columns. ```python # x and y given as array_like objects @@ -50,8 +50,8 @@ fig.show() ```python # x and y given as DataFrame columns import plotly.express as px -iris = px.data.iris() # iris is a pandas DataFrame -fig = px.scatter(iris, x="sepal_width", y="sepal_length") +df = px.data.iris() # iris is a pandas DataFrame +fig = px.scatter(df, x="sepal_width", y="sepal_length") fig.show() ``` @@ -61,8 +61,8 @@ Note that `color` and `size` data are added to hover information. You can add ot ```python import plotly.express as px -iris = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length", color="species", +df = px.data.iris() +fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", size='petal_length', hover_data=['petal_width']) fig.show() ``` @@ -81,15 +81,14 @@ fig.show() ```python import plotly.express as px -gapminder = px.data.gapminder().query("continent == 'Oceania'") -fig = px.line(gapminder, x='year', y='lifeExp', color='country') +df = px.data.gapminder().query("continent == 'Oceania'") +fig = px.line(df, x='year', y='lifeExp', color='country') fig.show() ``` ## Scatter and line plot with go.Scatter -If Plotly Express does not provide a good starting point, it is possible to use the more generic `go.Scatter` function from `plotly.graph_objects`. Whereas `plotly.express` has two functions `scatter` and `line`, `go.Scatter` can be used both for plotting points (makers) or lines, depending on the value of `mode`. The different options of `go.Scatter` are documented in its [reference page](https://plot.ly/python/reference/#scatter ). - +If Plotly Express does not provide a good starting point, it is possible to use the more generic `go.Scatter` function from `plotly.graph_objects`. Whereas `plotly.express` has two functions `scatter` and `line`, `go.Scatter` can be used both for plotting points (makers) or lines, depending on the value of `mode`. The different options of `go.Scatter` are documented in its [reference page](https://plot.ly/python/reference/#scatter). #### Simple Scatter Plot @@ -277,7 +276,6 @@ fig.show() ### Dash Example - [Dash](https://plot.ly/products/dash/) is an Open Source Python library which can help you convert plotly figures into a reactive, web-based application. Below is a simple example of a dashboard created using Dash. Its [source code](https://github.com/plotly/simple-example-chart-apps/tree/master/dash-linescatterplot) can easily be deployed to a PaaS. ```python @@ -292,4 +290,5 @@ IFrame(src= "https://dash-simple-apps.plotly.host/dash-linescatterplot/code", wi ``` ### Reference + See https://plot.ly/python/reference/#scatter or https://plot.ly/python/reference/#scattergl for more information and chart attribute options! diff --git a/doc/python/line-charts.md b/doc/python/line-charts.md index 413b5e8109a..d08dda0d45a 100644 --- a/doc/python/line-charts.md +++ b/doc/python/line-charts.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.1 kernelspec: display_name: Python 3 @@ -22,7 +22,8 @@ jupyter: pygments_lexer: ipython3 version: 3.6.7 plotly: - description: How to make line charts in Python with Plotly. Examples on creating + description: + How to make line charts in Python with Plotly. Examples on creating and styling line charts in Python with Plotly. display_as: basic language: python @@ -36,7 +37,7 @@ jupyter: ### Line Plot with plotly.express -[Plotly Express](/python/plotly-express/) is the easy-to-use, high-level interface to Plotly, which [operates on "tidy" data](/python/px-arguments/). With ``px.line``, each data point is represented as a vertex (which location is given by the `x` and `y` columns) of a **polyline mark** in 2D space. +[Plotly Express](/python/plotly-express/) is the easy-to-use, high-level interface to Plotly, which [operates on "tidy" data](/python/px-arguments/). With `px.line`, each data point is represented as a vertex (which location is given by the `x` and `y` columns) of a **polyline mark** in 2D space. For more examples of line plots, see the [line and scatter notebook](https://plot.ly/python/line-and-scatter/). @@ -45,8 +46,8 @@ For more examples of line plots, see the [line and scatter notebook](https://plo ```python import plotly.express as px -gapminder = px.data.gapminder().query("country=='Canada'") -fig = px.line(gapminder, x="year", y="lifeExp", title='Life expectancy in Canada') +df = px.data.gapminder().query("country=='Canada'") +fig = px.line(df, x="year", y="lifeExp", title='Life expectancy in Canada') fig.show() ``` @@ -55,24 +56,23 @@ fig.show() ```python import plotly.express as px -gapminder = px.data.gapminder().query("continent=='Oceania'") -fig = px.line(gapminder, x="year", y="lifeExp", color='country') +df = px.data.gapminder().query("continent=='Oceania'") +fig = px.line(df, x="year", y="lifeExp", color='country') fig.show() ``` ```python import plotly.express as px -gapminder = px.data.gapminder().query("continent != 'Asia'") # remove Asia for visibility -fig = px.line(gapminder, x="year", y="lifeExp", color="continent", +df = px.data.gapminder().query("continent != 'Asia'") # remove Asia for visibility +fig = px.line(df, x="year", y="lifeExp", color="continent", line_group="country", hover_name="country") fig.show() ``` ### Line Plot with go.Scatter -If Plotly Express does not provide a good starting point, it is possible to use the more generic `go.Scatter` function from `plotly.graph_objects`. Whereas `plotly.express` has two functions `scatter` and `line`, `go.Scatter` can be used both for plotting points (makers) or lines, depending on the value of `mode`. The different options of `go.Scatter` are documented in its [reference page](https://plot.ly/python/reference/#scatter ). - +If Plotly Express does not provide a good starting point, it is possible to use the more generic `go.Scatter` function from `plotly.graph_objects`. Whereas `plotly.express` has two functions `scatter` and `line`, `go.Scatter` can be used both for plotting points (makers) or lines, depending on the value of `mode`. The different options of `go.Scatter` are documented in its [reference page](https://plot.ly/python/reference/#scatter). #### Simple Line Plot @@ -120,7 +120,6 @@ fig.show() This example styles the color and dash of the traces, adds trace names, modifies line width, and adds plot and axes titles. - ```python import plotly.graph_objects as go @@ -161,6 +160,7 @@ fig.show() ``` #### Connect Data Gaps + [connectgaps](https://plot.ly/python/reference/#scatter-connectgaps) determines if missing values in the provided data are shown as a gap in the graph or not. In [this tutorial](https://plot.ly/python/filled-area-on-mapbox/#multiple-filled-areas-with-a-scattermapbox-trace), we showed how to take benefit of this feature and illustrate multiple areas in mapbox. ```python @@ -408,10 +408,8 @@ fig.show() ### Dash Example - [Dash](https://plot.ly/products/dash/) is an Open Source Python library which can help you convert plotly figures into a reactive, web-based application. Below is a simple example of a dashboard created using Dash. Its [source code](https://github.com/plotly/simple-example-chart-apps/tree/master/dash-lineplot) can easily be deployed to a PaaS. - ```python from IPython.display import IFrame IFrame(src= "https://dash-simple-apps.plotly.host/dash-lineplot/", width="100%", height="650px", frameBorder="0") @@ -425,4 +423,5 @@ IFrame(src= "https://dash-simple-apps.plotly.host/dash-lineplot/code", width="10 ``` #### Reference + See https://plot.ly/python/reference/#scatter for more information and chart attribute options! diff --git a/doc/python/linear-fits.md b/doc/python/linear-fits.md index d525e2dc166..795a334a7a6 100644 --- a/doc/python/linear-fits.md +++ b/doc/python/linear-fits.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.1 kernelspec: display_name: Python 3 @@ -22,7 +22,8 @@ jupyter: pygments_lexer: ipython3 version: 3.6.8 plotly: - description: Add linear Ordinary Least Squares (OLS) regression trendlines or non-linear + description: + Add linear Ordinary Least Squares (OLS) regression trendlines or non-linear Locally Weighted Scatterplot Smoothing (LOEWSS) trendlines to scatterplots in Python. display_as: statistical language: python @@ -40,12 +41,11 @@ jupyter: Plotly Express allows you to add [Ordinary Least](https://en.wikipedia.org/wiki/Ordinary_least_squares) Squares regression trendline to scatterplots with the `trendline` argument. In order to do so, you will need to install `statsmodels` and its dependencies. Hovering over the trendline will show the equation of the line and its R-squared value. - ```python import plotly.express as px -tips = px.data.tips() -fig = px.scatter(tips, x="total_bill", y="tip", trendline="ols") +df = px.data.tips() +fig = px.scatter(df, x="total_bill", y="tip", trendline="ols") fig.show() ``` @@ -56,8 +56,8 @@ Plotly Express will fit a trendline per trace, and allows you to access the unde ```python import plotly.express as px -tips = px.data.tips() -fig = px.scatter(tips, x="total_bill", y="tip", facet_col="smoker", color="sex", trendline="ols") +df = px.data.tips() +fig = px.scatter(df, x="total_bill", y="tip", facet_col="smoker", color="sex", trendline="ols") fig.show() results = px.get_trendline_results(fig) @@ -73,7 +73,7 @@ Plotly Express also supports non-linear [LOWESS](https://en.wikipedia.org/wiki/L ```python import plotly.express as px -gapminder = px.data.gapminder().query("year == 2007") -fig = px.scatter(gapminder, x="gdpPercap", y="lifeExp", color="continent", trendline="lowess") +df = px.data.gapminder().query("year == 2007") +fig = px.scatter(df, x="gdpPercap", y="lifeExp", color="continent", trendline="lowess") fig.show() ``` diff --git a/doc/python/lines-on-maps.md b/doc/python/lines-on-maps.md index a20a9aba7fe..b2e78985e28 100644 --- a/doc/python/lines-on-maps.md +++ b/doc/python/lines-on-maps.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.1 kernelspec: display_name: Python 3 @@ -43,8 +43,8 @@ Below we show how to create geographical line plots using either Plotly Express ```python import plotly.express as px -gapminder = px.data.gapminder().query("year == 2007") -fig = px.line_geo(gapminder, locations="iso_alpha", +df = px.data.gapminder().query("year == 2007") +fig = px.line_geo(df, locations="iso_alpha", color="continent", # "continent" is one of the columns of gapminder projection="orthographic") fig.show() @@ -212,4 +212,5 @@ fig.show() ``` #### Reference + See https://plot.ly/python/reference/#scattergeo for more information and chart attribute options! diff --git a/doc/python/marker-style.md b/doc/python/marker-style.md index 2287f9506a2..e456d7f41f9 100644 --- a/doc/python/marker-style.md +++ b/doc/python/marker-style.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.7 kernelspec: display_name: Python 3 @@ -41,8 +41,8 @@ Here is an example of adding a marker border to a faceted scatter plot created u ```python import plotly.express as px -iris = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length", color="species") +df = px.data.iris() +fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species") fig.update_traces(marker=dict(size=12, line=dict(width=2, @@ -107,10 +107,8 @@ fig.show() Fully opaque, the default setting, is useful for non-overlapping markers. When many points overlap it can be hard to observe density. - ### Opacity - Setting opacity outside the marker will set the opacity of the trace. Thus, it will allow greater visbility of additional traces but like fully opaque it is hard to distinguish density. ```python @@ -190,7 +188,6 @@ fig.show() ### Marker Opacity - To maximise visibility of density, it is recommended to set the opacity inside the marker `marker:{opacity:0.5}`. If mulitple traces exist with high density, consider using marker opacity in conjunction with trace opacity. ```python @@ -250,7 +247,6 @@ fig.show() ### Color Opacity - To maximise visibility of each point, set the color as an `rgba` string that includes an alpha value of 0.5. This example sets the marker color to `'rgba(135, 206, 250, 0.5)'`. The rgb values of 135, 206, and 250 are from the definition of the `LightSkyBlue` named CSS color that is is used in the previous examples (See https://www.color-hex.com/color/87cefa). The marker line will remain opaque. @@ -310,4 +306,5 @@ fig.show() ``` ### Reference + See https://plot.ly/python/reference/ for more information and chart attribute options! diff --git a/doc/python/parallel-categories-diagram.md b/doc/python/parallel-categories-diagram.md index 530b3b816f5..c368b5cb49b 100644 --- a/doc/python/parallel-categories-diagram.md +++ b/doc/python/parallel-categories-diagram.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.1 kernelspec: display_name: Python 3 @@ -34,41 +34,42 @@ jupyter: --- #### Parallel Categories Diagram -The parallel categories diagram is a visualization of multi-dimensional categorical data sets. Each variable in the data set is represented by a column of rectangles, where each rectangle corresponds to a discrete value taken on by that variable. The relative heights of the rectangles reflect the relative frequency of occurrence of the corresponding value. + +The parallel categories diagram is a visualization of multi-dimensional categorical data sets. Each variable in the data set is represented by a column of rectangles, where each rectangle corresponds to a discrete value taken on by that variable. The relative heights of the rectangles reflect the relative frequency of occurrence of the corresponding value. Combinations of category rectangles across dimensions are connected by ribbons, where the height of the ribbon corresponds to the relative frequency of occurrence of the combination of categories in the data set. For other representations of multivariate data, also see [parallel coordinates](/python/parallel-coordinates-plot/), [radar charts](/python/radar-chart/) and [scatterplot matrix (SPLOM)](/python/splom/). - #### Basic Parallel Category Diagram with plotly.express -This example visualizes the resturant bills of a sample of 244 people. Hovering over a category rectangle (sex, smoker, etc) displays a tooltip with the number of people with that single trait. Hovering over a ribbon in the diagram displays a tooltip with the number of people with a particular combination of the five traits connected by the ribbon. - +This example visualizes the resturant bills of a sample of 244 people. Hovering over a category rectangle (sex, smoker, etc) displays a tooltip with the number of people with that single trait. Hovering over a ribbon in the diagram displays a tooltip with the number of people with a particular combination of the five traits connected by the ribbon. ```python import plotly.express as px -tips = px.data.tips() -fig = px.parallel_categories(tips) +df = px.data.tips() +fig = px.parallel_categories(df) fig.show() ``` #### Style Diagram + In this example `dimensions` represents a list of stings or the columns of data frame, and `labels` is a dictionary with string keys (column name) and string values ('desired label to be displayed'). See [Plotly express reference page](https://www.plotly.express/plotly_express/#plotly_express.parallel_categories) for more information. ```python import plotly.express as px -tips = px.data.tips() -fig = px.parallel_categories(tips, dimensions=['sex', 'smoker', 'day'], +df = px.data.tips() +fig = px.parallel_categories(df, dimensions=['sex', 'smoker', 'day'], color="size", color_continuous_scale=px.colors.sequential.Inferno, labels={'sex':'Payer sex', 'smoker':'Smokers at the table', 'day':'Day of week'}) fig.show() ``` #### Basic Parallel Categories Diagram + This example illustartes the hair color, eye color, and sex of a sample of 8 people. The dimension labels can be dragged horizontally to reorder the dimensions and the category rectangles can be dragged vertically to reorder the categories within a dimension. ```python @@ -88,6 +89,7 @@ fig.show() ``` #### Basic Parallel Categories Diagram with Counts + If the frequency of occurrence for each combination of attributes is known in advance, this can be specified using the `counts` property ```python @@ -109,7 +111,8 @@ fig.show() ``` #### Mutli-Color Parallel Categories Diagram -The color of the ribbons can be specified with the `line.color` property. Similar to other trace types, this property may be set to an array of numbers, which are then mapped to colors according to the the colorscale specified in the `line.colorscale` property. + +The color of the ribbons can be specified with the `line.color` property. Similar to other trace types, this property may be set to an array of numbers, which are then mapped to colors according to the the colorscale specified in the `line.colorscale` property. Here is an example of visualizing the survival rate of passengers in the titanic dataset, where the ribbons are colored based on survival outcome. @@ -151,6 +154,7 @@ fig.show() ``` #### Parallel Categories Linked Brushing + This example demonstrates how the `on_selection` and `on_click` callbacks can be used to implement linked brushing between 3 categorical dimensions displayed with a `parcats` trace and 2 continuous dimensions displayed with a `scatter` trace. This example also sets the `line.shape` property to `hspline` to cause the ribbons to curve between categories. @@ -209,9 +213,9 @@ fig ![Single-color brushing](https://user-images.githubusercontent.com/15064365/48087050-4a3eae80-e1cc-11e8-94c9-c0ffcedd3aa9.gif) - #### Parallel Categories with Multi-Color Linked Brushing -This example extends the previous example to support brushing with multiple colors. The toggle buttons above may be used to select the active color, and this color will be applied when points are selected in the `scatter` trace and when categories or ribbons are clicked in the `parcats` trace. + +This example extends the previous example to support brushing with multiple colors. The toggle buttons above may be used to select the active color, and this color will be applied when points are selected in the `scatter` trace and when categories or ribbons are clicked in the `parcats` trace. ```python import plotly.graph_objects as go @@ -280,6 +284,6 @@ widgets.VBox([color_toggle, fig]) ![Multi-color brushing](https://user-images.githubusercontent.com/15064365/48087055-4e6acc00-e1cc-11e8-8f0c-c8316eb4def2.gif) - #### Reference + See [reference page](https://plot.ly/python/reference/#parcats) for more information and chart attribute options! diff --git a/doc/python/parallel-coordinates-plot.md b/doc/python/parallel-coordinates-plot.md index a76d0d8b963..ae9b9349ec4 100644 --- a/doc/python/parallel-coordinates-plot.md +++ b/doc/python/parallel-coordinates-plot.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.1 kernel_info: name: python2 @@ -41,8 +41,8 @@ jupyter: ```python import plotly.express as px -iris = px.data.iris() -fig = px.parallel_coordinates(iris, color="species_id", labels={"species_id": "Species", +df = px.data.iris() +fig = px.parallel_coordinates(df, color="species_id", labels={"species_id": "Species", "sepal_width": "Sepal Width", "sepal_length": "Sepal Length", "petal_width": "Petal Width", "petal_length": "Petal Length", }, color_continuous_scale=px.colors.diverging.Tealrose, @@ -56,8 +56,8 @@ Select the columns to be represented with the `dimensions` parameter. ```python import plotly.express as px -iris = px.data.iris() -fig = px.parallel_coordinates(iris, color="species_id", +df = px.data.iris() +fig = px.parallel_coordinates(df, color="species_id", dimensions=['sepal_width', 'sepal_length', 'petal_width', 'petal_length'], color_continuous_scale=px.colors.diverging.Tealrose, @@ -67,7 +67,6 @@ fig.show() ## Parallel Coordinates Chart with go.Parcoords - ```python inputHidden=false outputHidden=false import plotly.graph_objects as go @@ -95,10 +94,8 @@ fig.show() Parallel coordinates are richly interactive by default. Drag the lines along the axes to filter regions and drag the axis names across the plot to rearrange variables. - ![IPython terminal](https://s3-us-west-1.amazonaws.com/plotly-tutorials/plotly-documentation/images/python_parcoords_ex1.gif) - ### Basic Parallel Coordinates Plot ```python inputHidden=false outputHidden=false @@ -175,4 +172,5 @@ fig.show() ``` #### Reference + See https://plot.ly/python/reference/#parcoords for more information and chart attribute options! diff --git a/doc/python/plotly-express.md b/doc/python/plotly-express.md index ea7ffdd5508..ddb985d982b 100644 --- a/doc/python/plotly-express.md +++ b/doc/python/plotly-express.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.1 kernelspec: display_name: Python 3 @@ -22,7 +22,8 @@ jupyter: pygments_lexer: ipython3 version: 3.7.3 plotly: - description: Plotly Express is a terse, consistent, high-level API for rapid data + description: + Plotly Express is a terse, consistent, high-level API for rapid data exploration and figure generation. display_as: file_settings language: python @@ -56,67 +57,67 @@ px.data.iris().head() ```python import plotly.express as px -iris = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length") +df = px.data.iris() +fig = px.scatter(df, x="sepal_width", y="sepal_length") fig.show() ``` ```python import plotly.express as px -iris = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length", color="species") +df = px.data.iris() +fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species") fig.show() ``` ```python import plotly.express as px -iris = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length", color="species", marginal_y="rug", marginal_x="histogram") +df = px.data.iris() +fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", marginal_y="rug", marginal_x="histogram") fig ``` ```python import plotly.express as px -iris = px.data.iris() -fig = px.scatter(iris, x="sepal_width", y="sepal_length", color="species", marginal_y="violin", +df = px.data.iris() +fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", marginal_y="violin", marginal_x="box", trendline="ols") fig.show() ``` ```python import plotly.express as px -iris = px.data.iris() -iris["e"] = iris["sepal_width"]/100 -fig = px.scatter(iris, x="sepal_width", y="sepal_length", color="species", error_x="e", error_y="e") +df = px.data.iris() +df["e"] = df["sepal_width"]/100 +fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", error_x="e", error_y="e") fig.show() ``` ```python import plotly.express as px -tips = px.data.tips() -fig = px.scatter(tips, x="total_bill", y="tip", facet_row="time", facet_col="day", color="smoker", trendline="ols", +df = px.data.tips() +fig = px.scatter(df, x="total_bill", y="tip", facet_row="time", facet_col="day", color="smoker", trendline="ols", category_orders={"day": ["Thur", "Fri", "Sat", "Sun"], "time": ["Lunch", "Dinner"]}) fig.show() ``` ```python import plotly.express as px -iris = px.data.iris() -fig = px.scatter_matrix(iris) +df = px.data.iris() +fig = px.scatter_matrix(df) fig.show() ``` ```python import plotly.express as px -iris = px.data.iris() -fig = px.scatter_matrix(iris, dimensions=["sepal_width", "sepal_length", "petal_width", "petal_length"], color="species") +df = px.data.iris() +fig = px.scatter_matrix(df, dimensions=["sepal_width", "sepal_length", "petal_width", "petal_length"], color="species") fig.show() ``` ```python import plotly.express as px -iris = px.data.iris() -fig = px.parallel_coordinates(iris, color="species_id", labels={"species_id": "Species", +df = px.data.iris() +fig = px.parallel_coordinates(df, color="species_id", labels={"species_id": "Species", "sepal_width": "Sepal Width", "sepal_length": "Sepal Length", "petal_width": "Petal Width", "petal_length": "Petal Length", }, color_continuous_scale=px.colors.diverging.Tealrose, color_continuous_midpoint=2) @@ -125,31 +126,31 @@ fig.show() ```python import plotly.express as px -tips = px.data.tips() -fig = px.parallel_categories(tips, color="size", color_continuous_scale=px.colors.sequential.Inferno) +df = px.data.tips() +fig = px.parallel_categories(df, color="size", color_continuous_scale=px.colors.sequential.Inferno) fig.show() ``` ```python import plotly.express as px -tips = px.data.tips() -fig = px.scatter(tips, x="total_bill", y="tip", color="size", facet_col="sex", +df = px.data.tips() +fig = px.scatter(df, x="total_bill", y="tip", color="size", facet_col="sex", color_continuous_scale=px.colors.sequential.Viridis, render_mode="webgl") fig.show() ``` ```python import plotly.express as px -gapminder = px.data.gapminder() -fig = px.scatter(gapminder.query("year==2007"), x="gdpPercap", y="lifeExp", size="pop", color="continent", +df = px.data.gapminder() +fig = px.scatter(df.query("year==2007"), x="gdpPercap", y="lifeExp", size="pop", color="continent", hover_name="country", log_x=True, size_max=60) fig.show() ``` ```python import plotly.express as px -gapminder = px.data.gapminder() -fig = px.scatter(gapminder, x="gdpPercap", y="lifeExp", animation_frame="year", animation_group="country", +df = px.data.gapminder() +fig = px.scatter(df, x="gdpPercap", y="lifeExp", animation_frame="year", animation_group="country", size="pop", color="continent", hover_name="country", facet_col="continent", log_x=True, size_max=45, range_x=[100,100000], range_y=[25,90]) fig.show() @@ -157,16 +158,16 @@ fig.show() ```python import plotly.express as px -gapminder = px.data.gapminder() -fig = px.line(gapminder, x="year", y="lifeExp", color="continent", line_group="country", hover_name="country", +df = px.data.gapminder() +fig = px.line(df, x="year", y="lifeExp", color="continent", line_group="country", hover_name="country", line_shape="spline", render_mode="svg") fig.show() ``` ```python import plotly.express as px -gapminder = px.data.gapminder() -fig = px.area(gapminder, x="year", y="pop", color="continent", line_group="country") +df = px.data.gapminder() +fig = px.area(df, x="year", y="pop", color="continent", line_group="country") fig.show() ``` @@ -174,51 +175,51 @@ fig.show() ```python import plotly.express as px -iris = px.data.iris() -fig = px.density_contour(iris, x="sepal_width", y="sepal_length") +df = px.data.iris() +fig = px.density_contour(df, x="sepal_width", y="sepal_length") fig.show() ``` ```python import plotly.express as px -iris = px.data.iris() -fig = px.density_contour(iris, x="sepal_width", y="sepal_length", color="species", marginal_x="rug", marginal_y="histogram") +df = px.data.iris() +fig = px.density_contour(df, x="sepal_width", y="sepal_length", color="species", marginal_x="rug", marginal_y="histogram") fig.show() ``` ```python import plotly.express as px -iris = px.data.iris() -fig = px.density_heatmap(iris, x="sepal_width", y="sepal_length", marginal_x="rug", marginal_y="histogram") +df = px.data.iris() +fig = px.density_heatmap(df, x="sepal_width", y="sepal_length", marginal_x="rug", marginal_y="histogram") fig.show() ``` ```python import plotly.express as px -tips = px.data.tips() -fig = px.bar(tips, x="sex", y="total_bill", color="smoker", barmode="group") +df = px.data.tips() +fig = px.bar(df, x="sex", y="total_bill", color="smoker", barmode="group") fig.show() ``` ```python import plotly.express as px -tips = px.data.tips() -fig = px.bar(tips, x="sex", y="total_bill", color="smoker", barmode="group", facet_row="time", facet_col="day", +df = px.data.tips() +fig = px.bar(df, x="sex", y="total_bill", color="smoker", barmode="group", facet_row="time", facet_col="day", category_orders={"day": ["Thur", "Fri", "Sat", "Sun"], "time": ["Lunch", "Dinner"]}) fig.show() ``` ```python import plotly.express as px -tips = px.data.tips() -fig = px.histogram(tips, x="total_bill", y="tip", color="sex", marginal="rug", hover_data=tips.columns) +df = px.data.tips() +fig = px.histogram(df, x="total_bill", y="tip", color="sex", marginal="rug", hover_data=df.columns) fig.show() ``` ```python import plotly.express as px -tips = px.data.tips() -fig = px.histogram(tips, x="sex", y="tip", histfunc="avg", color="smoker", barmode="group", +df = px.data.tips() +fig = px.histogram(df, x="sex", y="tip", histfunc="avg", color="smoker", barmode="group", facet_row="time", facet_col="day", category_orders={"day": ["Thur", "Fri", "Sat", "Sun"], "time": ["Lunch", "Dinner"]}) fig.show() @@ -226,22 +227,22 @@ fig.show() ```python import plotly.express as px -tips = px.data.tips() -fig = px.strip(tips, x="total_bill", y="time", orientation="h", color="smoker") +df = px.data.tips() +fig = px.strip(df, x="total_bill", y="time", orientation="h", color="smoker") fig.show() ``` ```python import plotly.express as px -tips = px.data.tips() -fig = px.box(tips, x="day", y="total_bill", color="smoker", notched=True) +df = px.data.tips() +fig = px.box(df, x="day", y="total_bill", color="smoker", notched=True) fig.show() ``` ```python import plotly.express as px -tips = px.data.tips() -fig = px.violin(tips, y="tip", x="smoker", color="sex", box=True, points="all", hover_data=tips.columns) +df = px.data.tips() +fig = px.violin(df, y="tip", x="smoker", color="sex", box=True, points="all", hover_data=df.columns) fig.show() ``` @@ -249,16 +250,16 @@ fig.show() ```python import plotly.express as px -election = px.data.election() -fig = px.scatter_ternary(election, a="Joly", b="Coderre", c="Bergeron", color="winner", size="total", hover_name="district", +df = px.data.election() +fig = px.scatter_ternary(df, a="Joly", b="Coderre", c="Bergeron", color="winner", size="total", hover_name="district", size_max=15, color_discrete_map = {"Joly": "blue", "Bergeron": "green", "Coderre":"red"} ) fig.show() ``` ```python import plotly.express as px -election = px.data.election() -fig = px.line_ternary(election, a="Joly", b="Coderre", c="Bergeron", color="winner", line_dash="winner") +df = px.data.election() +fig = px.line_ternary(df, a="Joly", b="Coderre", c="Bergeron", color="winner", line_dash="winner") fig.show() ``` @@ -278,16 +279,16 @@ fig.show() ```python import plotly.express as px -election = px.data.election() -fig = px.scatter_3d(election, x="Joly", y="Coderre", z="Bergeron", color="winner", size="total", hover_name="district", +df = px.data.election() +fig = px.scatter_3d(df, x="Joly", y="Coderre", z="Bergeron", color="winner", size="total", hover_name="district", symbol="result", color_discrete_map = {"Joly": "blue", "Bergeron": "green", "Coderre":"red"}) fig.show() ``` ```python import plotly.express as px -election = px.data.election() -fig = px.line_3d(election, x="Joly", y="Coderre", z="Bergeron", color="winner", line_dash="winner") +df = px.data.election() +fig = px.line_3d(df, x="Joly", y="Coderre", z="Bergeron", color="winner", line_dash="winner") fig.show() ``` @@ -295,24 +296,24 @@ fig.show() ```python import plotly.express as px -wind = px.data.wind() -fig = px.scatter_polar(wind, r="frequency", theta="direction", color="strength", symbol="strength", +df = px.data.wind() +fig = px.scatter_polar(df, r="frequency", theta="direction", color="strength", symbol="strength", color_discrete_sequence=px.colors.sequential.Plasma[-2::-1]) fig.show() ``` ```python import plotly.express as px -wind = px.data.wind() -fig = px.line_polar(wind, r="frequency", theta="direction", color="strength", line_close=True, +df = px.data.wind() +fig = px.line_polar(df, r="frequency", theta="direction", color="strength", line_close=True, color_discrete_sequence=px.colors.sequential.Plasma[-2::-1]) fig.show() ``` ```python import plotly.express as px -wind = px.data.wind() -fig = px.bar_polar(wind, r="frequency", theta="direction", color="strength", template="plotly_dark", +df = px.data.wind() +fig = px.bar_polar(df, r="frequency", theta="direction", color="strength", template="plotly_dark", color_discrete_sequence= px.colors.sequential.Plasma[-2::-1]) fig.show() ``` @@ -322,8 +323,8 @@ fig.show() ```python import plotly.express as px px.set_mapbox_access_token(open(".mapbox_token").read()) -carshare = px.data.carshare() -fig = px.scatter_mapbox(carshare, lat="centroid_lat", lon="centroid_lon", color="peak_hour", size="car_hours", +df = px.data.carshare() +fig = px.scatter_mapbox(df, lat="centroid_lat", lon="centroid_lon", color="peak_hour", size="car_hours", color_continuous_scale=px.colors.cyclical.IceFire, size_max=15, zoom=10) fig.show() ``` @@ -331,30 +332,30 @@ fig.show() ```python import plotly.express as px px.set_mapbox_access_token(open(".mapbox_token").read()) -carshare = px.data.carshare() -fig = px.line_mapbox(carshare, lat="centroid_lat", lon="centroid_lon", color="peak_hour") +df = px.data.carshare() +fig = px.line_mapbox(df, lat="centroid_lat", lon="centroid_lon", color="peak_hour") fig.show() ``` ```python import plotly.express as px -gapminder = px.data.gapminder() -fig = px.scatter_geo(gapminder, locations="iso_alpha", color="continent", hover_name="country", size="pop", +df = px.data.gapminder() +fig = px.scatter_geo(df, locations="iso_alpha", color="continent", hover_name="country", size="pop", animation_frame="year", projection="natural earth") fig.show() ``` ```python import plotly.express as px -gapminder = px.data.gapminder() -fig = px.line_geo(gapminder.query("year==2007"), locations="iso_alpha", color="continent", projection="orthographic") +df = px.data.gapminder() +fig = px.line_geo(df.query("year==2007"), locations="iso_alpha", color="continent", projection="orthographic") fig.show() ``` ```python import plotly.express as px -gapminder = px.data.gapminder() -fig = px.choropleth(gapminder, locations="iso_alpha", color="lifeExp", hover_name="country", animation_frame="year", range_color=[20,80]) +df = px.data.gapminder() +fig = px.choropleth(df, locations="iso_alpha", color="lifeExp", hover_name="country", animation_frame="year", range_color=[20,80]) fig.show() ``` diff --git a/doc/python/polar-chart.md b/doc/python/polar-chart.md index 08019307d8f..b66e640bb95 100644 --- a/doc/python/polar-chart.md +++ b/doc/python/polar-chart.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.1 kernelspec: display_name: Python 3 @@ -39,14 +39,14 @@ A polar chart represents data along radial and angular axes. With Plotly Express [Plotly Express](/python/plotly-express/) is the easy-to-use, high-level interface to Plotly, which [operates on "tidy" data](/python/px-arguments/). - For other types of arguments, see the section below using `go.Scatterpolar`. +For other types of arguments, see the section below using `go.Scatterpolar`. The radial and angular coordinates are given with the `r` and `theta` arguments of `px.scatter_polar`. In the example below the `theta` data are categorical, but numerical data are possible too and the most common case. ```python import plotly.express as px -wind = px.data.wind() -fig = px.scatter_polar(wind, r="frequency", theta="direction") +df = px.data.wind() +fig = px.scatter_polar(df, r="frequency", theta="direction") fig.show() ``` @@ -54,8 +54,8 @@ The "strength" column corresponds to strength categories of the wind, and there ```python import plotly.express as px -wind = px.data.wind() -fig = px.scatter_polar(wind, r="frequency", theta="direction", +df = px.data.wind() +fig = px.scatter_polar(df, r="frequency", theta="direction", color="strength", symbol="strength", size="frequency", color_discrete_sequence=px.colors.sequential.Plasma[-2::-1]) fig.show() @@ -65,8 +65,8 @@ For a line polar plot, use `px.line_polar`: ```python import plotly.express as px -wind = px.data.wind() -fig = px.line_polar(wind, r="frequency", theta="direction", color="strength", line_close=True, +df = px.data.wind() +fig = px.line_polar(df, r="frequency", theta="direction", color="strength", line_close=True, color_discrete_sequence=px.colors.sequential.Plasma[-2::-1], template="plotly_dark",) fig.show() @@ -74,12 +74,11 @@ fig.show() See also the [wind rose page](https://plot.ly/python/wind-rose-charts/) for more wind rose visualizations in polar coordinates. - You can plot less than a whole circle with the `range_theta` argument, and also control the `start_angle` and `direction`: ```python import plotly.express as px -fig = px.scatter_polar(r=range(0,90,10), theta=range(0,90,10), +fig = px.scatter_polar(r=range(0,90,10), theta=range(0,90,10), range_theta=[0,90], start_angle=0, direction="counterclockwise") fig.show() ``` @@ -438,4 +437,5 @@ fig.show() ``` #### Reference + See https://plot.ly/python/reference/#scatterpolar for more information and chart attribute options! diff --git a/doc/python/px-arguments.md b/doc/python/px-arguments.md index c76ffe224eb..b55797a4dd4 100644 --- a/doc/python/px-arguments.md +++ b/doc/python/px-arguments.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.1 kernelspec: display_name: Python 3 @@ -72,18 +72,19 @@ fig.show() ```python import plotly.express as px -iris = px.data.iris() +df = px.data.iris() # Use directly Columns as argument. You can use tab completion for this! -fig = px.scatter(iris, x=iris.sepal_length, y=iris.sepal_width, color=iris.species, size=iris.petal_length) +fig = px.scatter(df, x=df.sepal_length, y=df.sepal_width, color=df.species, size=df.petal_length) fig.show() ``` + #### Passing name strings as arguments ```python import plotly.express as px -iris = px.data.iris() +df = px.data.iris() # Use column names instead. This is the same chart as above. -fig = px.scatter(iris, x='sepal_length', y='sepal_width', color='species', size='petal_length') +fig = px.scatter(df, x='sepal_length', y='sepal_width', color='species', size='petal_length') fig.show() ``` @@ -93,15 +94,15 @@ In addition to columns, it is also possible to pass the index of a DataFrame as ```python import plotly.express as px -iris = px.data.iris() -fig = px.scatter(iris, x=iris.sepal_length, y=iris.sepal_width, size=iris.petal_length, - hover_data=[iris.index]) +df = px.data.iris() +fig = px.scatter(df, x=df.sepal_length, y=df.sepal_width, size=df.petal_length, + hover_data=[df.index]) fig.show() ``` ### Columns not in the data_frame argument -In the addition to columns from the `data_frame` argument, one may also pass columns from a different DataFrame, *as long as all columns have the same length*. It is also possible to pass columns without passing the `data_frame` argument. +In the addition to columns from the `data_frame` argument, one may also pass columns from a different DataFrame, _as long as all columns have the same length_. It is also possible to pass columns without passing the `data_frame` argument. However, column names are used only if they correspond to columns in the `data_frame` argument, in other cases, the name of the keyword argument is used. As explained below, the `labels` argument can be used to set names. @@ -122,9 +123,9 @@ The `labels` argument can be used to override the names used for axis titles, le import plotly.express as px import pandas as pd -gapminder = px.data.gapminder() +df = px.data.gapminder() gdp = gapminder['pop'] * gapminder['gdpPercap'] -fig = px.bar(gapminder, x='year', y=gdp, color='continent', labels={'y':'gdp'}, +fig = px.bar(df, x='year', y=gdp, color='continent', labels={'y':'gdp'}, hover_data=['country'], title='Evolution of world GDP') fig.show() @@ -189,9 +190,9 @@ import plotly.express as px import numpy as np import pandas as pd -gapminder = px.data.gapminder() -gdp = np.log(gapminder['pop'] * gapminder['gdpPercap']) # NumPy array -fig = px.bar(gapminder, x='year', y=gdp, color='continent', labels={'y':'log gdp'}, +df = px.data.gapminder() +gdp = np.log(df['pop'] * gapminder['gdpPercap']) # NumPy array +fig = px.bar(df, x='year', y=gdp, color='continent', labels={'y':'log gdp'}, hover_data=['country'], title='Evolution of world GDP') fig.show() diff --git a/doc/python/scatter-plots-on-maps.md b/doc/python/scatter-plots-on-maps.md index 451b5519128..df82f99f885 100644 --- a/doc/python/scatter-plots-on-maps.md +++ b/doc/python/scatter-plots-on-maps.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.1 kernelspec: display_name: Python 3 @@ -22,7 +22,8 @@ jupyter: pygments_lexer: ipython3 version: 3.6.7 plotly: - description: How to make scatter plots on maps in Python. Scatter plots on maps + description: + How to make scatter plots on maps in Python. Scatter plots on maps highlight geographic areas and can be colored by value. display_as: maps language: python @@ -42,8 +43,8 @@ Here we show the [Plotly Express](/python/plotly-express/) function `px.scatter_ ```python import plotly.express as px -gapminder = px.data.gapminder().query("year == 2007") -fig = px.scatter_geo(gapminder, locations="iso_alpha", +df = px.data.gapminder().query("year == 2007") +fig = px.scatter_geo(df, locations="iso_alpha", size="pop", # size of markers, "pop" is one of the columns of gapminder ) fig.show() @@ -53,8 +54,8 @@ fig.show() ```python import plotly.express as px -gapminder = px.data.gapminder().query("year == 2007") -fig = px.scatter_geo(gapminder, locations="iso_alpha", +df = px.data.gapminder().query("year == 2007") +fig = px.scatter_geo(df, locations="iso_alpha", color="continent", # which column to use to set the color of markers hover_name="country", # column added to hover information size="pop", # size of markers @@ -209,4 +210,5 @@ fig.show() ``` #### Reference -See https://plot.ly/python/reference/#scattergeo and https://plot.ly/python/reference/#layout-geo for more information and chart attribute options! + +See https://plot.ly/python/reference/#scattergeo and https://plot.ly/python/reference/#layout-geo for more information and chart attribute options! diff --git a/doc/python/scattermapbox.md b/doc/python/scattermapbox.md index 9dcec0b2263..f1978fec57c 100644 --- a/doc/python/scattermapbox.md +++ b/doc/python/scattermapbox.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.1 kernelspec: display_name: Python 3 @@ -36,7 +36,7 @@ jupyter: #### Mapbox Access Token -To plot on Mapbox maps with Plotly you *may* need a Mapbox account and a public [Mapbox Access Token](https://www.mapbox.com/studio). See our [Mapbox Map Layers](/python/mapbox-layers/) documentation for more information. +To plot on Mapbox maps with Plotly you _may_ need a Mapbox account and a public [Mapbox Access Token](https://www.mapbox.com/studio). See our [Mapbox Map Layers](/python/mapbox-layers/) documentation for more information. ### Basic example with Plotly Express @@ -47,8 +47,8 @@ Here we show the [Plotly Express](/python/plotly-express/) function `px.scatter_ ```python import plotly.express as px px.set_mapbox_access_token(open(".mapbox_token").read()) -carshare = px.data.carshare() -fig = px.scatter_mapbox(carshare, lat="centroid_lat", lon="centroid_lon", color="peak_hour", size="car_hours", +df = px.data.carshare() +fig = px.scatter_mapbox(df, lat="centroid_lat", lon="centroid_lon", color="peak_hour", size="car_hours", color_continuous_scale=px.colors.cyclical.IceFire, size_max=15, zoom=10) fig.show() ``` @@ -198,6 +198,7 @@ fig.show() ### Set Marker Symbols You can define a symbol on your map by setting [symbol](https://plot.ly/python/reference/#scattermapbox-marker-symbol) attribute. This attribute only works on Mapbox-provided `style`s: + - basic - streets - outdoors @@ -227,4 +228,5 @@ fig.show() ``` #### Reference + See https://plot.ly/python/reference/#scattermapbox for more information and options! diff --git a/doc/python/setting-graph-size.md b/doc/python/setting-graph-size.md index 2234b4a9085..a2d3e51821d 100644 --- a/doc/python/setting-graph-size.md +++ b/doc/python/setting-graph-size.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.7 kernelspec: display_name: Python 3 @@ -37,8 +37,8 @@ jupyter: ```python import plotly.express as px -tips = px.data.tips() -fig = px.scatter(tips, x="total_bill", y="tip", facet_col="sex", +df = px.data.tips() +fig = px.scatter(df, x="total_bill", y="tip", facet_col="sex", width=800, height=400) fig.update_layout( @@ -49,7 +49,7 @@ fig.update_layout( fig.show() ``` -### Adjusting Height, Width, & Margins ### +### Adjusting Height, Width, & Margins ```python import plotly.graph_objects as go @@ -80,7 +80,6 @@ fig.show() ### Automatically Adjust Margins - Set [automargin](https://plot.ly/python/reference/#layout-xaxis-automargin) to `True` and Plotly will automatically increase the margin size to prevent ticklabels from being cut off or overlapping with axis titles. ```python @@ -113,4 +112,5 @@ fig.show() ``` #### Reference + See https://plot.ly/python/reference/#layout for more information and chart attribute options! diff --git a/doc/python/splom.md b/doc/python/splom.md index 474b1c8a4c4..0101ebfb094 100644 --- a/doc/python/splom.md +++ b/doc/python/splom.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.1 kernelspec: display_name: Python 3 @@ -22,7 +22,8 @@ jupyter: pygments_lexer: ipython3 version: 3.6.7 plotly: - description: How to make scatterplot matrices or sploms natively in Python with + description: + How to make scatterplot matrices or sploms natively in Python with Plotly. display_as: statistical language: python @@ -37,7 +38,7 @@ jupyter: ### Scatter matrix with Plotly Express -A scatterplot matrix is a matrix associated to n numerical arrays (data variables), $X_1,X_2,…,X_n$ , of the same length. The cell (i,j) of such a matrix displays the scatter plot of the variable Xi versus Xj. +A scatterplot matrix is a matrix associated to n numerical arrays (data variables), $X_1,X_2,…,X_n$ , of the same length. The cell (i,j) of such a matrix displays the scatter plot of the variable Xi versus Xj. Here we show the Plotly Express function `px.scatter_matrix` to plot the scatter matrix for the columns of the dataframe. By default, all columns are considered. @@ -45,8 +46,8 @@ Here we show the Plotly Express function `px.scatter_matrix` to plot the scatter ```python import plotly.express as px -iris = px.data.iris() -fig = px.scatter_matrix(iris) +df = px.data.iris() +fig = px.scatter_matrix(df) fig.show() ``` @@ -54,8 +55,8 @@ Specify the columns to be represented with the `dimensions` argument, and set co ```python import plotly.express as px -iris = px.data.iris() -fig = px.scatter_matrix(iris, +df = px.data.iris() +fig = px.scatter_matrix(df, dimensions=["sepal_width", "sepal_length", "petal_width", "petal_length"], color="species") fig.show() @@ -67,22 +68,23 @@ The scatter matrix plot can be configured thanks to the parameters of `px.scatte ```python import plotly.express as px -iris = px.data.iris() -fig = px.scatter_matrix(iris, +df = px.data.iris() +fig = px.scatter_matrix(df, dimensions=["sepal_width", "sepal_length", "petal_width", "petal_length"], color="species", symbol="species", title="Scatter matrix of iris data set", - labels={col:col.replace('_', ' ') for col in iris.columns}) # remove underscore + labels={col:col.replace('_', ' ') for col in df.columns}) # remove underscore fig.update_traces(diagonal_visible=False) fig.show() ``` + ### Scatter matrix (splom) with go.Splom If Plotly Express does not provide a good starting point, it is possible to use the more generic `go.Splom` function. All its parameters are documented in the reference page https://plot.ly/python/reference/#splom. -The Plotly splom trace implementation for the scatterplot matrix does not require to set $x=Xi$ , and $y=Xj$, for each scatter plot. All arrays, $X_1,X_2,…,X_n$ , are passed once, through a list of dicts called dimensions, i.e. each array/variable represents a dimension. +The Plotly splom trace implementation for the scatterplot matrix does not require to set $x=Xi$ , and $y=Xj$, for each scatter plot. All arrays, $X_1,X_2,…,X_n$ , are passed once, through a list of dicts called dimensions, i.e. each array/variable represents a dimension. A trace of type `splom` is defined as follows: @@ -101,6 +103,7 @@ trace=go.Splom(dimensions=[dict(label='string-1', ``` The label in each dimension is assigned to the axes titles of the corresponding matrix cell. + #### Splom of the Iris data set diff --git a/doc/python/templates.md b/doc/python/templates.md index e8b37c5186a..fbf8e438816 100644 --- a/doc/python/templates.md +++ b/doc/python/templates.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.6 kernelspec: display_name: Python 3 @@ -34,12 +34,15 @@ jupyter: --- ### Theming and templates + The Plotly Python library comes pre-loaded with several themes that you can get started using right away, and it also provides support for creating and registering your own themes. -> Note on terminology: Theming generally refers to the process of defining default styles for visual elements. Themes in plotly are implemented using objects called templates. Templates are slightly more general than traditional themes because in addition to defining default styles, templates can pre-populate a figure with visual elements like annotations, shapes, images, and more. In the documentation we will refer to the overall process of defining default styles as theming, and when in comes to the plotly API we will talk about how themes are implemented using templates. +> Note on terminology: Theming generally refers to the process of defining default styles for visual elements. Themes in plotly are implemented using objects called templates. Templates are slightly more general than traditional themes because in addition to defining default styles, templates can pre-populate a figure with visual elements like annotations, shapes, images, and more. In the documentation we will refer to the overall process of defining default styles as theming, and when in comes to the plotly API we will talk about how themes are implemented using templates. ### Using built-in themes + #### View available themes + To see information about the available themes and the current default theme, display the `plotly.io.templates` configuration object like this. ```python @@ -49,18 +52,18 @@ pio.templates From this, we can see that the default theme is `"plotly"`, and we can see the names of several additional themes that we can choose from. - #### Specifying themes in Plotly Express + All Plotly Express functions accept a `template` argument that can be set to the name of a registered theme (or to a `Template` object as discussed later in this section). Here is an example of using Plotly Express to build and display the same scatter plot with six different themes. ```python import plotly.express as px -gapminder = px.data.gapminder() -gapminder_2007 = gapminder.query("year==2007") +df = px.data.gapminder() +df_2007 = df.query("year==2007") for template in ["plotly", "plotly_white", "plotly_dark", "ggplot2", "seaborn", "simple_white", "none"]: - fig = px.scatter(gapminder_2007, + fig = px.scatter(df_2007, x="gdpPercap", y="lifeExp", size="pop", color="continent", log_x=True, size_max=60, template=template, title="Gapminder 2007: '%s' theme" % template) @@ -68,6 +71,7 @@ for template in ["plotly", "plotly_white", "plotly_dark", "ggplot2", "seaborn", ``` #### Specifying themes in graph object figures + The theme for a particular graph object figure can be specified by setting the `template` property of the figure's `layout` to the name of a registered theme (or to a `Template` object as discussed later in this section). Here is an example of constructing a surface plot and then displaying it with each of six themes. ```python @@ -90,7 +94,8 @@ for template in ["plotly", "plotly_white", "plotly_dark", "ggplot2", "seaborn", ``` #### Specifying a default themes -If a theme is not provided to a Plotly Express function or to a graph object figure, then the default theme is used. The default theme starts out as `"plotly"`, but it can be changed by setting the `plotly.io.templates.default` property to the name of a registered theme. + +If a theme is not provided to a Plotly Express function or to a graph object figure, then the default theme is used. The default theme starts out as `"plotly"`, but it can be changed by setting the `plotly.io.templates.default` property to the name of a registered theme. Here is an example of changing to default theme to `"plotly_white"` and then constructing a scatter plot with Plotly Express without providing a template. @@ -102,10 +107,10 @@ import plotly.express as px pio.templates.default = "plotly_white" -gapminder = px.data.gapminder() -gapminder_2007 = gapminder.query("year==2007") +df = px.data.gapminder() +df_2007 = df.query("year==2007") -fig = px.scatter(gapminder_2007, +fig = px.scatter(df_2007, x="gdpPercap", y="lifeExp", size="pop", color="continent", log_x=True, size_max=60, title="Gapminder 2007: current default theme") @@ -113,6 +118,7 @@ fig.show() ``` #### Disable default theming + If you do not wish to use any of the new themes by default, or you want your figures to look exactly the way they did prior to plotly.py version 4, you can disable default theming by setting the default theme to `"none"`. ```python @@ -121,12 +127,14 @@ pio.templates.default = "none" ``` ### Creating themes + #### Representing themes with Template objects -Themes in plotly.py are represented by instances of the `Template` class from the `plotly.graph_objects.layout` module. A `Template` is a graph object that contains two top-level properties: `layout` and `data`. These template properties are described in their own sections below. +Themes in plotly.py are represented by instances of the `Template` class from the `plotly.graph_objects.layout` module. A `Template` is a graph object that contains two top-level properties: `layout` and `data`. These template properties are described in their own sections below. #### The template layout property -The `layout` property of a template is a graph object with the exact same structure as the `layout` property of a figure. When you provide values for properties of the template's `layout`, these values will be used as the defaults in any figure that this template is applied to. + +The `layout` property of a template is a graph object with the exact same structure as the `layout` property of a figure. When you provide values for properties of the template's `layout`, these values will be used as the defaults in any figure that this template is applied to. Here is an example that creates a template that sets the default title font to size 24 Rockwell, and then constructs a graph object figure with this template. @@ -146,7 +154,8 @@ fig.show() > Note: this example uses magic underscore notation to write `go.Layout(title=dict(font=dict(...)))` as `go.Layout(title_font=dict(...))` #### The template data property -The `data` property of a template is used to customize the default values of the properties of traces that are added to a figure that the template is applied to. This `data` property holds a graph object, with type `go.layout.template.Data`, that has a property named after each supported trace type. These trace type properties are then assigned lists or tuples of graph object traces of the corresponding type. + +The `data` property of a template is used to customize the default values of the properties of traces that are added to a figure that the template is applied to. This `data` property holds a graph object, with type `go.layout.template.Data`, that has a property named after each supported trace type. These trace type properties are then assigned lists or tuples of graph object traces of the corresponding type. Here is an example that creates a template that sets the default scatter trace markers to be size 20 diamonds, and then constructs a graph object figure with this template. @@ -162,7 +171,7 @@ fig.add_scatter(y=[2, 1, 3], mode="markers") fig.show() ``` -If a trace type property is set to a list of more than one trace, then the default properties are cycled as more traces are added to the figure. Here is an example that creates a template that cycles the default marker symbol for scatter traces, and then constructs a figure that uses this template. +If a trace type property is set to a list of more than one trace, then the default properties are cycled as more traces are added to the figure. Here is an example that creates a template that cycles the default marker symbol for scatter traces, and then constructs a figure that uses this template. ```python import plotly.graph_objects as go @@ -185,11 +194,11 @@ fig.show() Note that because we built the template with a list of 3 scatter trace graph objects (one each for the diamond, square, and circle symbols), the forth scatter trace in the figure cycles around and takes on the defaults specified in the first template trace (The diamond symbol). - #### Theming object tuple properties -Some properties in the figure hierarchy are specified as tuples of objects. For example, the text annotations for a graph object figure are stored as a tuple of `go.layout.Annotation` objects in the `annotations` property of the figure's layout. -To use a template to configure the default properties of all of the elements in an object tuple property (e.g. `layout.annotations`), use the `*defaults` property in the template that corresponds to the tuple property (e.g. `layout.template.layout.annotationdefaults`). The `*defaults` template property should be set to a single graph object that matches the type of the elements of the corresponding tuple. The properties of this `*defaults` object in the template will be applied to all elements of the object tuple in the figure that the template is applied to. +Some properties in the figure hierarchy are specified as tuples of objects. For example, the text annotations for a graph object figure are stored as a tuple of `go.layout.Annotation` objects in the `annotations` property of the figure's layout. + +To use a template to configure the default properties of all of the elements in an object tuple property (e.g. `layout.annotations`), use the `*defaults` property in the template that corresponds to the tuple property (e.g. `layout.template.layout.annotationdefaults`). The `*defaults` template property should be set to a single graph object that matches the type of the elements of the corresponding tuple. The properties of this `*defaults` object in the template will be applied to all elements of the object tuple in the figure that the template is applied to. Here is an example that creates a template that specifies the default annotation text color, and then constructs a figure that uses this template. @@ -212,9 +221,9 @@ fig.show() #### Including tuple elements in a theme -The previous section described how to use a template to customize the default properties of tuple elements that are added to a figure that the template is applied to. This is useful for styling, for example, any annotations, shapes, or images that will eventually be added to the figure. +The previous section described how to use a template to customize the default properties of tuple elements that are added to a figure that the template is applied to. This is useful for styling, for example, any annotations, shapes, or images that will eventually be added to the figure. -It is also possible for a template to define tuple elements that should be included, as is, in any figure that the template is applied to. This is done by specifying a list of one or more tuple element graph objects (e.g. `go.layout.Annotation` objects) as the value of the corresponding tuple property in the template (e.g. at `template.layout.annotations`). Note that the `name` property of these tuple element graph objects must be set to a unique non-empty string. +It is also possible for a template to define tuple elements that should be included, as is, in any figure that the template is applied to. This is done by specifying a list of one or more tuple element graph objects (e.g. `go.layout.Annotation` objects) as the value of the corresponding tuple property in the template (e.g. at `template.layout.annotations`). Note that the `name` property of these tuple element graph objects must be set to a unique non-empty string. Here is an example that creates a template that adds a large semi-transparent "DRAFT" watermark to the middle of the figure, and constructs a figure using this template. @@ -243,7 +252,8 @@ fig.show() ``` #### Customizing theme tuple elements in a figure -The previous section described how a template can be used to add default tuple element graph objects (e.g. annotations, shapes, or images) to a figure. The properties of these default tuple elements can be customized from within the figure by adding an tuple element with a `templateitemname` property that matches the `name` property of the template object. + +The previous section described how a template can be used to add default tuple element graph objects (e.g. annotations, shapes, or images) to a figure. The properties of these default tuple elements can be customized from within the figure by adding an tuple element with a `templateitemname` property that matches the `name` property of the template object. Here is an example, using the same `draft_template` defined above, that customizes the watermark from within the figure to read "CONFIDENTIAL" rather than "DRAFT". @@ -280,9 +290,10 @@ fig.show() ``` #### Registering themes as named templates -The examples above construct and configure a `Template` object and then pass that object as the template specification to graph object figures (as the `layout.template` property) or Plotly Express functions (as the `template` keyword argument). It is also possible to register custom templates by name so that the name itself can be used to refer to the template. To register a template, use dictionary-style assignment to associate the template object with a name in the `plotly.io.templates` configuration object. -Here is an example of registering the draft watermark template from the previous sections as a template named `"draft"`. Then a graph object figure is created with the draft template specified by name. +The examples above construct and configure a `Template` object and then pass that object as the template specification to graph object figures (as the `layout.template` property) or Plotly Express functions (as the `template` keyword argument). It is also possible to register custom templates by name so that the name itself can be used to refer to the template. To register a template, use dictionary-style assignment to associate the template object with a name in the `plotly.io.templates` configuration object. + +Here is an example of registering the draft watermark template from the previous sections as a template named `"draft"`. Then a graph object figure is created with the draft template specified by name. ```python import plotly.graph_objects as go @@ -341,7 +352,8 @@ fig.show() ``` #### Combining themes -You may have noticed that figures displayed with the custom templates defined above do not have the gray background and white gridlines that are part of the default styling of figures created with plotly.py. The reason for this is that the default styling is specified in a template named `"plotly"`, and specifying a custom template overrides the default `"plotly"` template. + +You may have noticed that figures displayed with the custom templates defined above do not have the gray background and white gridlines that are part of the default styling of figures created with plotly.py. The reason for this is that the default styling is specified in a template named `"plotly"`, and specifying a custom template overrides the default `"plotly"` template. If you want the styling of a custom template to be applied on top of the default styling of the `"plotly"` template, then you will need to combine the custom template with the `"plotly"` template. Multiple registered templates (whether built-in or user-defined) can be combined by specifying a template string that contains multiple template names joined on `"+"` characters. @@ -397,10 +409,10 @@ pio.templates["draft"] = go.layout.Template( ) pio.templates.default = "plotly+draft" -gapminder = px.data.gapminder() -gapminder_2007 = gapminder.query("year==2007") +df = px.data.gapminder() +df_2007 = df.query("year==2007") -fig = px.scatter(gapminder_2007, +fig = px.scatter(df_2007, x="gdpPercap", y="lifeExp", size="pop", color="continent", log_x=True, size_max=60, title="Gapminder 2007: current default theme") @@ -408,12 +420,15 @@ fig.show() ``` + #### Saving and distributing custom themes -The easiest way to save and distribute a custom template is to make a `*.py` file that creates and registers the template when it is imported. Here is an example of the contents of a file called `my_themes.py` that creates and registers the `"draft"` template when it is imported + +The easiest way to save and distribute a custom template is to make a `*.py` file that creates and registers the template when it is imported. Here is an example of the contents of a file called `my_themes.py` that creates and registers the `"draft"` template when it is imported **my_themes.py** --- + ```python import plotly.graph_objects as go import plotly.io as pio @@ -435,6 +450,7 @@ pio.templates["draft"] = go.layout.Template( ] ) ``` + --- To get access to the `"draft"` template, import the `my_themes` module. @@ -447,10 +463,12 @@ pio.templates.default = "draft" ``` > Note: In order for the import to succeed, the `my_themes.py` file must be on Python's module search path. See https://docs.python.org/3/tutorial/modules.html#the-module-search-path for more information. + #### Examining built-in themes -It may be useful to examine the contents and structure of the built-in templates when creating your own custom templates. The `Template` graph object for a registered template can be loaded using dictionary-style key access on the `plotly.io.templates` configuration object. Here is an example of loading the `Template` graph object for the `"plotly"` template, and then displaying the value of the template's `layout` property. + +It may be useful to examine the contents and structure of the built-in templates when creating your own custom templates. The `Template` graph object for a registered template can be loaded using dictionary-style key access on the `plotly.io.templates` configuration object. Here is an example of loading the `Template` graph object for the `"plotly"` template, and then displaying the value of the template's `layout` property. ```python import plotly.io as pio diff --git a/doc/python/text-and-annotations.md b/doc/python/text-and-annotations.md index 7a90b3d6e2f..80892f3cb3e 100644 --- a/doc/python/text-and-annotations.md +++ b/doc/python/text-and-annotations.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.2.1 kernelspec: display_name: Python 3 @@ -39,9 +39,9 @@ Here is an example that creates a scatter plot with text labels using Plotly Exp ```python import plotly.express as px -gapminder = px.data.gapminder().query("year==2007 and continent=='Americas'") +df = px.data.gapminder().query("year==2007 and continent=='Americas'") -fig = px.scatter(gapminder, x="gdpPercap", y="lifeExp", text="country", log_x=True, size_max=60) +fig = px.scatter(df, x="gdpPercap", y="lifeExp", text="country", log_x=True, size_max=60) fig.update_traces(textposition='top center') @@ -503,8 +503,8 @@ fig.update_layout( fig.show() ``` - ### Customize Displayed Text with a Text Template + To show an arbitrary text in your chart you can use [texttemplate](https://plot.ly/python/reference/#pie-texttemplate), which is a template string used for rendering the information, and will override [textinfo](https://plot.ly/python/reference/#treemap-textinfo). This template string can include `variables` in %{variable} format, `numbers` in [d3-format's syntax](https://github.com/d3/d3-3.x-api-reference/blob/master/Formatting.md#d3_forma), and `date` in [d3-time-fomrat's syntax](https://github.com/d3/d3-3.x-api-reference/blob/master/Time-Formatting.md#format). `texttemplate` customizes the text that appears on your plot vs. [hovertemplate](https://plot.ly/python/reference/#pie-hovertemplate) that customizes the tooltip text. @@ -541,7 +541,9 @@ fig = go.Figure(go.Scatterternary( fig.show() ``` + ### Set Date in Text Template + The following example shows how to show date by setting [axis.type](https://plot.ly/python/reference/#layout-yaxis-type) in [funnel charts](https://plot.ly/python/funnel-charts/). As you can see [textinfo](https://plot.ly/python/reference/#funnel-textinfo) and [texttemplate](https://plot.ly/python/reference/#funnel-texttemplate) have the same functionality when you want to determine 'just' the trace information on the graph. @@ -572,4 +574,5 @@ fig.show() ``` #### Reference + See https://plot.ly/python/reference/#layout-annotations for more information and chart attribute options! diff --git a/doc/python/violin.md b/doc/python/violin.md index aed469fee17..9665755b5ed 100644 --- a/doc/python/violin.md +++ b/doc/python/violin.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.1 kernelspec: display_name: Python 3 @@ -47,8 +47,8 @@ See also the [list of other statistical charts](https://plot.ly/python/statistic ```python import plotly.express as px -tips = px.data.tips() -fig = px.violin(tips, y="total_bill") +df = px.data.tips() +fig = px.violin(df, y="total_bill") fig.show() ``` @@ -57,8 +57,8 @@ fig.show() ```python import plotly.express as px -tips = px.data.tips() -fig = px.violin(tips, y="total_bill", box=True, # draw box plot inside the violin +df = px.data.tips() +fig = px.violin(df, y="total_bill", box=True, # draw box plot inside the violin points='all', # can be 'outliers', or False ) fig.show() @@ -69,20 +69,20 @@ fig.show() ```python import plotly.express as px -tips = px.data.tips() -fig = px.violin(tips, y="tip", x="smoker", color="sex", box=True, points="all", - hover_data=tips.columns) +df = px.data.tips() +fig = px.violin(df, y="tip", x="smoker", color="sex", box=True, points="all", + hover_data=df.columns) fig.show() ``` ```python import plotly.express as px -tips = px.data.tips() -fig = px.violin(tips, y="tip", color="sex", +df = px.data.tips() +fig = px.violin(df, y="tip", color="sex", violinmode='overlay', # draw violins on top of each other # default violinmode is 'group' as in example above - hover_data=tips.columns) + hover_data=df.columns) fig.show() ``` @@ -259,4 +259,5 @@ fig.show() ``` #### Reference + See https://plot.ly/python/reference/#violin for more information and chart attribute options! diff --git a/doc/python/wind-rose-charts.md b/doc/python/wind-rose-charts.md index 02e31c9e278..3c9f3189bfd 100644 --- a/doc/python/wind-rose-charts.md +++ b/doc/python/wind-rose-charts.md @@ -5,7 +5,7 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' + format_version: "1.1" jupytext_version: 1.1.1 kernelspec: display_name: Python 3 @@ -22,7 +22,8 @@ jupyter: pygments_lexer: ipython3 version: 3.6.7 plotly: - description: How to graph wind rose charts in python. Wind Rose charts display + description: + How to graph wind rose charts in python. Wind Rose charts display wind speed and direction of a given location. display_as: scientific language: python @@ -42,8 +43,8 @@ A [wind rose chart](https://en.wikipedia.org/wiki/Wind_rose) (also known as a po ```python import plotly.express as px -wind = px.data.wind() -fig = px.bar_polar(wind, r="frequency", theta="direction", +df = px.data.wind() +fig = px.bar_polar(df, r="frequency", theta="direction", color="strength", template="plotly_dark", color_discrete_sequence= px.colors.sequential.Plasma[-2::-1]) fig.show() From db5979a1f80f293aed93628be1e1945568e0c523 Mon Sep 17 00:00:00 2001 From: Nicolas Kruchten Date: Tue, 17 Dec 2019 10:51:42 -0500 Subject: [PATCH 04/10] hurray for tests --- doc/python/px-arguments.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/python/px-arguments.md b/doc/python/px-arguments.md index b55797a4dd4..add81956987 100644 --- a/doc/python/px-arguments.md +++ b/doc/python/px-arguments.md @@ -124,7 +124,7 @@ import plotly.express as px import pandas as pd df = px.data.gapminder() -gdp = gapminder['pop'] * gapminder['gdpPercap'] +gdp = df['pop'] * df['gdpPercap'] fig = px.bar(df, x='year', y=gdp, color='continent', labels={'y':'gdp'}, hover_data=['country'], title='Evolution of world GDP') @@ -191,7 +191,7 @@ import numpy as np import pandas as pd df = px.data.gapminder() -gdp = np.log(df['pop'] * gapminder['gdpPercap']) # NumPy array +gdp = np.log(df['pop'] * df['gdpPercap']) # NumPy array fig = px.bar(df, x='year', y=gdp, color='continent', labels={'y':'log gdp'}, hover_data=['country'], title='Evolution of world GDP') From e667b1a3abbc9a1ba33b54ed17f70e3e9fafb65e Mon Sep 17 00:00:00 2001 From: Emmanuelle Gouillart Date: Wed, 18 Dec 2019 22:40:40 -0500 Subject: [PATCH 05/10] mention PIL in Layout image tutorial (#2004) --- doc/python/images.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/doc/python/images.md b/doc/python/images.md index 79e2625e612..4bf287df16c 100644 --- a/doc/python/images.md +++ b/doc/python/images.md @@ -37,6 +37,11 @@ jupyter: In this page we explain how to add static, non-interactive images as background, logo or annotation images to a figure. For exploring image data in interactive charts, see the [tutorial on displaying image data](/python/imshow). +A background image can be added to the layout of a figure with +`fig.add_layout_image` or by setting the `images` parameter of `go.Layout`. The +`source` attribute of a `go.layout.Image` can be the URL of an image, or a PIL +Image object (`from PIL import Image; img = Image.open('filename.png')`). + ```python import plotly.graph_objects as go From 6669d3e4bcc2cef031095904c6849babc1b21a25 Mon Sep 17 00:00:00 2001 From: Emmanuelle Gouillart Date: Fri, 20 Dec 2019 13:30:29 -0500 Subject: [PATCH 06/10] removed outdated comments about offline in configuration tutorial (#2013) --- doc/python/configuration-options.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/doc/python/configuration-options.md b/doc/python/configuration-options.md index e09d50146d6..89eedba9805 100644 --- a/doc/python/configuration-options.md +++ b/doc/python/configuration-options.md @@ -22,8 +22,7 @@ jupyter: pygments_lexer: ipython3 version: 3.7.3 plotly: - description: How to set configuration options of plotly graphs in python. Examples - of both online and offline configurations. + description: How to set configuration options of plotly graphs in python. display_as: file_settings language: python layout: base @@ -34,8 +33,8 @@ jupyter: thumbnail: thumbnail/modebar-icons.png --- -#### Offline Configuration Options -Now you can pass a `config` dictionary with all configurations options such as `scrollZoom`, `editable`, and `displayModeBar`. For the complete list of config options check out: https://github.com/plotly/plotly.js/blob/master/src/plot_api/plot_config.js + +You can pass a `config` dictionary with all configurations options such as `scrollZoom`, `editable`, and `displayModeBar`. For the complete list of config options check out: https://github.com/plotly/plotly.js/blob/master/src/plot_api/plot_config.js ##### Enable Scroll Zoom From be25a7bd9bb445420d641ae8889a538618caecaf Mon Sep 17 00:00:00 2001 From: Nicolas Kruchten Date: Thu, 26 Dec 2019 22:37:23 -0500 Subject: [PATCH 07/10] adding built-in colorscales reference page --- doc/python/builtin-colorscales.md | 108 ++++++++++++++++++++++++++++++ doc/python/colorscales.md | 4 +- 2 files changed, 110 insertions(+), 2 deletions(-) create mode 100644 doc/python/builtin-colorscales.md diff --git a/doc/python/builtin-colorscales.md b/doc/python/builtin-colorscales.md new file mode 100644 index 00000000000..80fcb40b7b0 --- /dev/null +++ b/doc/python/builtin-colorscales.md @@ -0,0 +1,108 @@ +--- +jupyter: + jupytext: + notebook_metadata_filter: all + text_representation: + extension: .md + format_name: markdown + format_version: "1.2" + jupytext_version: 1.3.0 + kernelspec: + display_name: Python 3 + language: python + name: python3 + language_info: + codemirror_mode: + name: ipython + version: 3 + file_extension: .py + mimetype: text/x-python + name: python + nbconvert_exporter: python + pygments_lexer: ipython3 + version: 3.7.3 + plotly: + description: A reference for the built-in named continuous (sequential, diverging and cylclical) colorscales in Plotly. + display_as: file_settings + has_thumbnail: true + ipynb: ~notebook_demo/187 + language: python + layout: base + name: Built-in Continuous Colorscales + order: 26 + permalink: python/builtin-colorscales/ + thumbnail: thumbnail/heatmap_colorscale.jpg + v4upgrade: true +--- + +### Using Built-In Colorscales + +Many Plotly Express functions accept a `color_continuous_scale` argument and many trace +types have a `colorscale` attribute in their schema. Plotly comes with a large number of +built-in continuous colorscales, which can be referred to in Python code when setting the above arguments, +either by name in a case-insensitive string e.g. `px.scatter(continuous_color_scale="Viridis"`) or by reference e.g. +`go.Scatter(marker_colorscale=plotly.colors.sequential.Viridis)`. They can also be reversed by adding `_r` at the end +e.g. `"Viridis_r"` or `plotly.colors.sequential.Viridis_r`. + +The `plotly.colours` module is also available under `plotly.express.colors` so you can refer to it as `px.colors`. + +When using continuous colorscales, you will often want to [configure various aspects of its range and colorbar](/python/colorscales/). + +### Named Built-In Colorscales + +You can use any of the following names as string values to set `continuous_color_scale` or `colorscale` arguments. +These strings are case-insensitive and you can append `_r` to them to reverse the order of the scale. + +```python +import plotly.express as px + +print("".join('{:<12}'.format(c) for c in px.colors.named_colorscales())) +``` + +### Built-In Sequential Colorscales + +A collection of predefined sequential colorscales is provided in the `plotly.colors.sequential` module. Sequential color scales are appropriate for most continuous data, but in some cases it can be helpful to use a diverging or cyclical color scale (see below). + +Here are all the built-in scales in the `plotly.colors.sequential` module: + +```python +import plotly.express as px + +fig = px.colors.sequential.swatches() +fig.show() +``` + +Note: `RdBu` was included in this module by mistake, even though it is a diverging color scale. +It is intentionally left in for backwards-compatibility reasons. + +### Built-In Diverging Colorscales + +A collection of predefined diverging colorscales is provided in the `plotly.colors.diverging` module. +Diverging color scales are appropriate for continuous data that has a natural midpoint +other otherwise informative special value, such as 0 altitude, or the boiling point +of a liquid. These scales are intended to be used when [explicitly setting the midpoint of the scale](/python/colorscales/#setting-the-midpoint-of-a-diverging-colorscale). + +Here are all the built-in scales in the `plotly.colors.diverging` module: + +```python +import plotly.express as px + +fig = px.colors.diverging.swatches() +fig.show() +``` + +### Built-In Cyclical Colorscales + +A collection of predefined cyclical colorscales is provided in the `plotly.colors.cyclical` module. +Cyclical color scales are appropriate for continuous data that has a natural cyclical +structure, such as temporal data (hour of day, day of week, day of year, seasons) or +complex numbers or other phase or angular data. + +Here are all the built-in scales in the `plotly.colors.cyclical` module: + +```python +import plotly.express as px + +fig = px.colors.cyclical.swatches() +fig.show() +``` diff --git a/doc/python/colorscales.md b/doc/python/colorscales.md index e5c4795729a..be5fb2a2309 100644 --- a/doc/python/colorscales.md +++ b/doc/python/colorscales.md @@ -6,7 +6,7 @@ jupyter: extension: .md format_name: markdown format_version: "1.2" - jupytext_version: 1.3.0 + jupytext_version: 1.3.1 kernelspec: display_name: Python 3 language: python @@ -20,7 +20,7 @@ jupyter: name: python nbconvert_exporter: python pygments_lexer: ipython3 - version: 3.7.3 + version: 3.6.8 plotly: description: How to set colorscales and heatmap colorscales in Python and Plotly. From b298008b9b8b8561e5bee4ce6c389a46f093bbcd Mon Sep 17 00:00:00 2001 From: Nicolas Kruchten Date: Thu, 26 Dec 2019 22:40:54 -0500 Subject: [PATCH 08/10] crosslinking --- doc/python/colorscales.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/doc/python/colorscales.md b/doc/python/colorscales.md index be5fb2a2309..b51081bd5cf 100644 --- a/doc/python/colorscales.md +++ b/doc/python/colorscales.md @@ -38,9 +38,11 @@ jupyter: v4upgrade: true --- -### Predefined colorscales in Plotly Express +### Built-In Colorscales -A collection of predefined sequential colorscales is provided in the `plotly.express.colors.sequential` module. +Plotly comes with a large number of [Built-in Continuous Colorscales](/python/builtin-colorscales/). + +### Using Built-In Colorscales in Plotly Express Here is an example that creates a scatter plot using Plotly Express, with points colored using the Viridis colorscale. From 1f9a756563bf31d4c6488a1ae8928d596a4df7ee Mon Sep 17 00:00:00 2001 From: Nicolas Kruchten Date: Thu, 26 Dec 2019 22:42:42 -0500 Subject: [PATCH 09/10] fix CI --- doc/python/builtin-colorscales.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/python/builtin-colorscales.md b/doc/python/builtin-colorscales.md index 80fcb40b7b0..3677495c127 100644 --- a/doc/python/builtin-colorscales.md +++ b/doc/python/builtin-colorscales.md @@ -29,7 +29,7 @@ jupyter: language: python layout: base name: Built-in Continuous Colorscales - order: 26 + order: 27 permalink: python/builtin-colorscales/ thumbnail: thumbnail/heatmap_colorscale.jpg v4upgrade: true From bf7426ca557671bb6acb1c4e89f631335e843a9c Mon Sep 17 00:00:00 2001 From: Nicolas Kruchten Date: Thu, 26 Dec 2019 23:06:46 -0500 Subject: [PATCH 10/10] better wrapping --- doc/python/builtin-colorscales.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/doc/python/builtin-colorscales.md b/doc/python/builtin-colorscales.md index 3677495c127..0363100c401 100644 --- a/doc/python/builtin-colorscales.md +++ b/doc/python/builtin-colorscales.md @@ -5,8 +5,8 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: "1.2" - jupytext_version: 1.3.0 + format_version: '1.2' + jupytext_version: 1.3.1 kernelspec: display_name: Python 3 language: python @@ -20,9 +20,10 @@ jupyter: name: python nbconvert_exporter: python pygments_lexer: ipython3 - version: 3.7.3 + version: 3.6.8 plotly: - description: A reference for the built-in named continuous (sequential, diverging and cylclical) colorscales in Plotly. + description: A reference for the built-in named continuous (sequential, diverging + and cylclical) colorscales in Plotly. display_as: file_settings has_thumbnail: true ipynb: ~notebook_demo/187 @@ -55,8 +56,10 @@ These strings are case-insensitive and you can append `_r` to them to reverse th ```python import plotly.express as px +from textwrap import wrap -print("".join('{:<12}'.format(c) for c in px.colors.named_colorscales())) +named_colorscales = px.colors.named_colorscales() +print("\n".join(wrap("".join('{:<12}'.format(c) for c in named_colorscales), 96))) ``` ### Built-In Sequential Colorscales