Skip to content

Doc prod #2799

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Oct 1, 2020
347 changes: 138 additions & 209 deletions doc/python/axes.md

Large diffs are not rendered by default.

6 changes: 4 additions & 2 deletions doc/python/bar-charts.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ jupyter:
extension: .md
format_name: markdown
format_version: '1.2'
jupytext_version: 1.3.4
jupytext_version: 1.4.2
kernelspec:
display_name: Python 3
language: python
Expand All @@ -20,7 +20,7 @@ jupyter:
name: python
nbconvert_exporter: python
pygments_lexer: ipython3
version: 3.7.0
version: 3.7.7
plotly:
description: How to make Bar Charts in Python with Plotly.
display_as: basic
Expand Down Expand Up @@ -112,6 +112,7 @@ fig.show()
```python
# Change the default stacking
import plotly.express as px
df = px.data.tips()
fig = px.bar(df, x="sex", y="total_bill",
color='smoker', barmode='group',
height=400)
Expand All @@ -124,6 +125,7 @@ Use the keyword arguments `facet_row` (resp. `facet_col`) to create facetted sub

```python
import plotly.express as px
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"],
Expand Down
191 changes: 191 additions & 0 deletions doc/python/categorical-axes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
---
jupyter:
jupytext:
notebook_metadata_filter: all
text_representation:
extension: .md
format_name: markdown
format_version: '1.2'
jupytext_version: 1.4.2
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.7
plotly:
description: How to use categorical axes in Python with Plotly.
display_as: basic
language: python
layout: base
name: Categorical Axes
order: 16
page_type: example_index
permalink: python/categorical-axes/
thumbnail: thumbnail/bar.jpg
---


This page shows examples of how to configure [2-dimensional Cartesian axes](/python/figure-structure/#2d-cartesian-trace-types-and-subplots) to visualize categorical (i.e. qualitative, nominal or ordinal data as opposed to continuous numerical data). Such axes are a natural fit for bar charts, waterfall charts, funnel charts, heatmaps, violin charts and box plots, but can also be used with scatter plots and line charts. [Configuring gridlines, ticks, tick labels and axis titles](/python/axes/) on logarithmic axes is done the same was as with [linear axes](/python/axes/).

### 2-D Cartesian Axis Type and Auto-Detection

The different types of Cartesian axes are configured via the `xaxis.type` or `yaxis.type` attribute, which can take on the following values:

- `'linear'` (see the [linear axes tutoria](/python/axes/))
- `'log'` (see the [log plot tutorial](/python/log-plots/))
- `'date'` (see the [tutorial on timeseries](/python/time-series/))
- `'category'` see below
- `'multicategory'` see below

The axis type is auto-detected by looking at data from the first [trace](/python/figure-structure/) linked to this axis:

* First check for `multicategory`, then `date`, then `category`, else default to `linear` (`log` is never automatically selected)
* `multicategory` is just a shape test: is the array nested?
* `date` and `category`: require **more than twice as many distinct date or category strings** as distinct numbers or numeric strings in order to choose that axis type.
* Both of these test an evenly-spaced sample of at most 1000 values
* Small detail: the `category` test sorts every value into either number or category, whereas for dates, 2- and 4-digit integers count as both dates and numbers.


### Forcing an axis to be categorical

If you pass string values for the `x` or `y` parameter, plotly will automatically set the corresponding axis type to `category`, *except if enough of these strings contain numbers* as detailed above, in which case the axis is automatically set to `linear`. It is however possible to force the axis type by setting explicitely `xaxis_type` to be `category`.

```python
import plotly.express as px
fig = px.bar(x=[1, 2, 4, 10], y =[8, 6, 11, 5])
fig.update_xaxes(type='category')
fig.show()
```

### Controlling the Category Order with Plotly Express

[Plotly Express](/python/plotly-express/) is the easy-to-use, high-level interface to Plotly, which [operates on a variety of types of data](/python/px-arguments/) and produces [easy-to-style figures](/python/styling-plotly-express/).

By default, Plotly Express lays out categorical data in the order in which it appears in the underlying data. Every 2-d cartesian Plotly Express function also includes a `category_orders` keyword argument which can be used to control the order in which categorical axes are drawn, but beyond that can also control [the order in which discrete colors appear in the legend](/python/discrete-color/), and [the order in which facets are laid out](/python/facet-plots/).

```python
import plotly.express as px
df = px.data.tips()
fig = px.bar(df, x="day", y="total_bill", color="smoker", barmode="group", facet_col="sex",
category_orders={"day": ["Thur", "Fri", "Sat", "Sun"],
"smoker": ["Yes", "No"],
"sex": ["Male", "Female"]})
fig.show()
```

### Automatically Sorting Categories by Name or Total Value

Whether using Plotly Express or not, categories can be sorted alphabetically or by value using the `categoryorder` attribute:

Set `categoryorder` to `"category ascending"` or `"category descending"` for the alphanumerical order of the category names or `"total ascending"` or `"total descending"` for numerical order of values. [categoryorder](https://plotly.com/python/reference/layout/xaxis/#layout-xaxis-categoryorder) for more information. Note that sorting the bars by a particular trace isn't possible right now - it's only possible to sort by the total values. Of course, you can always sort your data _before_ plotting it if you need more customization.

This example orders the categories **alphabetically** with `categoryorder: 'category ascending'`

```python
import plotly.graph_objects as go

x=['b', 'a', 'c', 'd']
fig = go.Figure(go.Bar(x=x, y=[2,5,1,9], name='Montreal'))
fig.add_trace(go.Bar(x=x, y=[1, 4, 9, 16], name='Ottawa'))
fig.add_trace(go.Bar(x=x, y=[6, 8, 4.5, 8], name='Toronto'))

fig.update_layout(barmode='stack')
fig.update_xaxes(categoryorder='category ascending')
fig.show()
```

This example orders the categories **by total value** with `categoryorder: 'total descending'`

```python
import plotly.graph_objects as go

x=['b', 'a', 'c', 'd']
fig = go.Figure(go.Bar(x=x, y=[2,5,1,9], name='Montreal'))
fig.add_trace(go.Bar(x=x, y=[1, 4, 9, 16], name='Ottawa'))
fig.add_trace(go.Bar(x=x, y=[6, 8, 4.5, 8], name='Toronto'))

fig.update_layout(barmode='stack')
fig.update_xaxes(categoryorder='total ascending')
fig.show()
```

This example shows how to control category order when using `plotly.graph_objects` by defining `categoryorder` to "array" to derive the ordering from the attribute `categoryarray`.

```python
import plotly.graph_objects as go

x=['b', 'a', 'c', 'd']
fig = go.Figure(go.Bar(x=x, y=[2,5,1,9], name='Montreal'))
fig.add_trace(go.Bar(x=x, y=[1, 4, 9, 16], name='Ottawa'))
fig.add_trace(go.Bar(x=x, y=[6, 8, 4.5, 8], name='Toronto'))

fig.update_layout(barmode='stack')
fig.update_xaxes(categoryorder='array', categoryarray= ['d','a','c','b'])
fig.show()
```
### Gridlines, Ticks and Tick Labels


By default, gridlines and ticks are not shown on categorical axes but they can be activated:

```python
import plotly.express as px

fig = px.bar(x=["A","B","C"], y=[1,3,2])
fig.update_xaxes(showgrid=True, ticks="outside")
fig.show()
```

By default, ticks and gridlines appear on the categories but the `tickson` attribute can be used to move them to the category boundaries:

```python
import plotly.express as px

fig = px.bar(x=["A","B","C"], y=[1,3,2])
fig.update_xaxes(showgrid=True, ticks="outside", tickson="boundaries")
fig.show()
```

### Multi-categorical Axes

A two-level categorical axis (also known as grouped or hierarchical categories, or sub-categories) 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. This is only possible with `plotly.graph_objects` at the moment, and not Plotly Express.

Passing in a two-dimensional list as the `x` or `y` value of a trace causes [the `type` of the corresponding axis](/python/axes/) to be set to `multicategory`.

Here is an example that creates a figure with 2 `bar` traces with a 2-level categorical x-axis.

```python
import plotly.graph_objects as go

fig = go.Figure()

fig.add_trace(go.Bar(
x = [['First', 'First', 'Second', 'Second'],
["A", "B", "A", "B"]],
y = [2, 3, 1, 5],
name = "Adults",
))

fig.add_trace(go.Bar(
x = [['First', 'First', 'Second', 'Second'],
["A", "B", "A", "B"]],
y = [8, 3, 6, 5],
name = "Children",
))

fig.update_layout(title_text="Multi-category axis")

fig.show()
```
### Reference

See https://plotly.com/python/reference/layout/xaxis/ for more information and chart attribute options!
20 changes: 17 additions & 3 deletions doc/python/facet-plots.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ fig.show()

Since subplot figure titles are [annotations](https://plotly.com/python/text-and-annotations/#simple-annotation), you can use the `for_each_annotation` function to customize them, for example to remove the equal-sign (`=`).

In the following example, we pass a lambda function to `for_each_annotation` in order to change the figure subplot titles from `smoker=No` and `smoker=Yes` to just `No` and `Yes`.
In the following example, we pass a lambda function to `for_each_annotation` in order to change the figure subplot titles from `smoker=No` and `smoker=Yes` to just `No` and `Yes`.

```python
import plotly.express as px
Expand All @@ -117,9 +117,23 @@ fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1]))
fig.show()
```

### Controlling Facet Ordering

By default, Plotly Express lays out categorical data in the order in which it appears in the underlying data. Every 2-d cartesian Plotly Express function also includes a `category_orders` keyword argument which can be used to control [the order in which categorical axes are drawn](/python/categorical-axes/), but beyond that can also control [the order in which discrete colors appear in the legend](/python/discrete-color/), and the order in which facets are laid out.

```python
import plotly.express as px
df = px.data.tips()
fig = px.bar(df, x="day", y="total_bill", color="smoker", barmode="group", facet_col="sex",
category_orders={"day": ["Thur", "Fri", "Sat", "Sun"],
"smoker": ["Yes", "No"],
"sex": ["Male", "Female"]})
fig.show()
```

### Controlling Facet Spacing

The `facet_row_spacing` and `facet_col_spacing` arguments can be used to control the spacing between rows and columns. These values are specified in fractions of the plotting area in paper coordinates and not in pixels, so they will grow or shrink with the `width` and `height` of the figure.
The `facet_row_spacing` and `facet_col_spacing` arguments can be used to control the spacing between rows and columns. These values are specified in fractions of the plotting area in paper coordinates and not in pixels, so they will grow or shrink with the `width` and `height` of the figure.

The defaults work well with 1-4 rows or columns at the default figure size with the default font size, but need to be reduced to around 0.01 for very large figures or figures with many rows or columns. Conversely, if activating tick labels on all facets, the spacing will need to be increased.

Expand All @@ -140,7 +154,7 @@ fig.show()

### Synchronizing axes in subplots with `matches`

Using `facet_col` from `plotly.express` let [zoom](https://help.plotly.com/zoom-pan-hover-controls/#step-3-zoom-in-and-zoom-out-autoscale-the-plot) and [pan](https://help.plotly.com/zoom-pan-hover-controls/#step-6-pan-along-axes) each facet to the same range implicitly. However, if the subplots are created with `make_subplots`, the axis needs to be updated with `matches` parameter to update all the subplots accordingly.
Using `facet_col` from `plotly.express` let [zoom](https://help.plotly.com/zoom-pan-hover-controls/#step-3-zoom-in-and-zoom-out-autoscale-the-plot) and [pan](https://help.plotly.com/zoom-pan-hover-controls/#step-6-pan-along-axes) each facet to the same range implicitly. However, if the subplots are created with `make_subplots`, the axis needs to be updated with `matches` parameter to update all the subplots accordingly.

Zoom in one trace below, to see the other subplots zoomed to the same x-axis range. To pan all the subplots, click and drag from the center of x-axis to the side:

Expand Down
4 changes: 2 additions & 2 deletions doc/python/figure-factories.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,9 @@ The following types of plots are still difficult to create with Graph Objects or
Deprecated "legacy" Figure Factories include:

* [County Choropleth Maps](/python/county-choropleth/), deprecated by regular [Choropleth maps with GeoJSON input](/python/choropleth-maps/)
* [Distplots](/python/distplot/), mostly deprecated by [`px.histogram`](/python/histograms/)
* [Distplots](/python/distplot/), mostly deprecated by [`px.histogram`](/python/histograms/) except for KDE plots, which `px.histogram` doesn't support yet
* [Gantt Charts](/python/gantt/), deprecated by [`px.timeline`](/python/gantt/)

#### Reference

For more information about the contents of `plotly.figure_factory`, including deprecated methods, please refer to our [API Reference documentation](https://plotly.com/python-api-reference/plotly.figure_factory.html).
For more information about the contents of `plotly.figure_factory`, including deprecated methods, please refer to our [API Reference documentation](https://plotly.com/python-api-reference/plotly.figure_factory.html).
2 changes: 1 addition & 1 deletion doc/python/figure-structure.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ The following trace types are compatible with 2d-cartesian subplots via the `xax
* scatter-like trace types: [`scatter`](/python/line-and-scatter/) and [`scattergl`](/python/webgl-vs-svg/), which can be used to draw [scatter plots](/python/line-and-scatter/), [line plots and curves](/python/line-charts/), [time-series plots](/python/time-series/), [bubble charts](/python/bubble-charts/), [dot plots](/python/dot-plots/) and [filled areas](/python/filled-area-plots/) and also support [error bars](/python/error-bars/)
* [`bar`](/python/bar-charts/), [`funnel`](/python/funnel-charts/), [`waterfall`](/python/waterfall-charts/): bar-like trace types which can also be used to draw [timelines and Gantt charts](/python/gantt/)
* [`histogram`](/python/histograms/): an *aggregating* bar-like trace type
* [`box`](/python/box-plots/) and `violin`: 1-dimensional distribution-like trace types
* [`box`](/python/box-plots/) and [`violin`](/python/box-plots/): 1-dimensional distribution-like trace types
* [`histogram2d`](/python/2D-Histogram/) and [`histogram2dcontour`](/python/2d-histogram-contour/): 2-dimensional distribution-like density trace types
* [`image`](/python/imshow/), [`heatmap`](/python/heatmaps/) and [`contour`](/python/contour-plots/): matrix trace types
* [`ohlc`](/python/ohlc-charts/) and [`candlestick`](/python/candlestick-charts/): stock-like trace types
Expand Down
6 changes: 4 additions & 2 deletions doc/python/histograms.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ jupyter:
order: 3
page_type: example_index
permalink: python/histograms/
redirect_from: /python/histogram-tutorial/
redirect_from:
- /python/histogram-tutorial/
- /python/histogram/
thumbnail: thumbnail/histogram.jpg
---

Expand Down Expand Up @@ -392,4 +394,4 @@ fig.show()

#### Reference

See https://plotly.com/python/reference/histogram/ for more information and chart attribute options!
See https://plotly.com/python/reference/histogram/ for more information and chart attribute options!
42 changes: 41 additions & 1 deletion doc/python/legend.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,46 @@ fig = px.scatter(df, x="total_bill", y="tip", color="sex", symbol="smoker", face
fig.show()
```

### Legend Order

By default, Plotly Express lays out legend items in the order in which values appear in the underlying data. Every Plotly Express function also includes a `category_orders` keyword argument which can be used to control [the order in which categorical axes are drawn](/python/categorical-axes/), but beyond that can also control the order in which legend items appear, and [the order in which facets are laid out](/python/facet-plots/).

```python
import plotly.express as px
df = px.data.tips()
fig = px.bar(df, x="day", y="total_bill", color="smoker", barmode="group", facet_col="sex",
category_orders={"day": ["Thur", "Fri", "Sat", "Sun"],
"smoker": ["Yes", "No"],
"sex": ["Male", "Female"]})
fig.show()
```

When using stacked bars, the bars are stacked from the bottom in the same order as they appear in the legend, so it can make sense to set `layout.legend.traceorder` to `"reversed"` to get the legend and stacks to match:

```python
import plotly.express as px
df = px.data.tips()
fig = px.bar(df, x="day", y="total_bill", color="smoker", barmode="stack", facet_col="sex",
category_orders={"day": ["Thur", "Fri", "Sat", "Sun"],
"smoker": ["Yes", "No"],
"sex": ["Male", "Female"]})
fig.update_layout(legend_traceorder="reversed")
fig.show()
```

When using [`plotly.graph_objects`](/python/graph-objects/) rather than Plotly Express, legend items will appear in the order that traces appear in the `data`:

```python
import plotly.graph_objects as go

fig = go.Figure()
fig.add_trace(go.Bar(name="first", x=["a", "b"], y=[1,2]))
fig.add_trace(go.Bar(name="second", x=["a", "b"], y=[2,1]))
fig.add_trace(go.Bar(name="third", x=["a", "b"], y=[1,2]))
fig.add_trace(go.Bar(name="fourth", x=["a", "b"], y=[2,1]))
fig.show()
```

#### Showing and Hiding the Legend

By default the legend is displayed on Plotly charts with multiple traces, and this can be explicitly set with the `layout.showlegend` attribute:
Expand Down Expand Up @@ -419,4 +459,4 @@ fig.show()

#### Reference

See https://plotly.com/python/reference/layout/#layout-legend for more information!
See https://plotly.com/python/reference/layout/#layout-legend for more information!
Loading