Skip to content

big batch of layout.geo docs #2109

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 4 commits into from
Jan 22, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,4 @@ plotly/tests/test_orca/images/*/tmp
temp-plot.html
.vscode
doc/python/.ipynb_checkpoints
doc/python/.mapbox_token
35 changes: 16 additions & 19 deletions doc/python/axes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -34,23 +35,24 @@ jupyter:
thumbnail: thumbnail/axes.png
---

This tutorial explain how to set the properties of Cartesian axes, namely [`go.layout.XAxis`](/python/reference/#layout-xaxis) and [`go.layout.YAxis`](python/reference/#layout-xaxis). Other kinds of axes are described in other tutorials:
This tutorial explain how to set the properties of 2-dimensional Cartesian axes, namely [`go.layout.XAxis`](/python/reference/#layout-xaxis) and [`go.layout.YAxis`](python/reference/#layout-xaxis). Other kinds of axes are described in other tutorials:

- [3D axes](/python/3d-axes) The axis object is [`go.layout.Scene`](/python/reference/#layout-scene)
- [Polar axes](/python/polar-chart/). The axis object is [`go.layout.Polar`](/python/reference/#layout-polar)
- [Ternary axes](/python/ternary-plots). The axis object is [`go.layout.Ternary`](/python/reference/#layout-ternary)
- For Geo axes, see [this choropleth example](/python/choropleth-maps/#world-choropleth-map). The axis object is [`go.layout.Geo`](/python/reference/#layout-geo)
- For Mapbox axes, see the different mapbox tutorials in the [Maps page](/python/maps/). The axis object is [`go.layout.Mapbox`](/python/reference/#layout-mapbox)
- Color axes are described in the [color scales tutorial](/python/colorscales/).
- [Geo axes](/python/map-configuration/). The axis object is [`go.layout.Geo`](/python/reference/#layout-geo)
- [Mapbox axes](/python/mapbox-layers/). The axis object is [`go.layout.Mapbox`](/python/reference/#layout-mapbox)
- [Color axes](/python/colorscales/). The axis object is [`go.layout.Coloraxis`](/python/reference/#layout-coloraxis).

**See also** the tutorials on [subplots](/python/subplots) and [multiple axes](/python/multiple-axes/).

The different types of Cartesian axes are
The different types of Cartesian axes are

- 'linear'
- 'log' (see the [example below](#logarithmic-axes))
- 'date' (see the [tutorial on timeseries](/python/time-series/))
- 'category' (see for example [Bar Charts](/python/bar-charts/))
- 'multicategory' (see the [example below](#subcategory-(multicategory)-axes) ))

- 'multicategory' (see the [example below](<#subcategory-(multicategory)-axes>))

#### Logarithmic Axes

Expand Down Expand Up @@ -92,7 +94,7 @@ fig.show()

### 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`, with the exception of string of numbers, in which case the axis is linear. It is however possible to force the axis type by setting explicitely `xaxis_type` to be `category`.
If you pass string values for the `x` or `y` parameter, plotly will automatically set the corresponding axis type to `category`, with the exception of string of numbers, in which case the axis is linear. It is however possible to force the axis type by setting explicitely `xaxis_type` to be `category`.

```python
import plotly.express as px
Expand Down Expand Up @@ -150,17 +152,16 @@ fig.update_layout(title_text="Multi-category axis",)
fig.show()
```


#### Toggling Axes Lines, Ticks, Labels, and Autorange

The different groups of Cartesian axes properties are
The different groups of Cartesian axes properties are

- tick values (locations of tick marks) and tick labels. Tick labels are placed at tick values.
- lines: grid lines (passing through tick values), axis lines, zero lines
- title of the axis
- range of the axis
- domain of the axis


#### Tick Placement, Color, and Style

##### Toggling axis tick marks
Expand All @@ -169,7 +170,6 @@ Axis tick marks are disabled by default for the default `plotly` theme, but they

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
df = px.data.iris()
Expand Down Expand Up @@ -265,7 +265,6 @@ fig.update_yaxes(showticklabels=False)
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.
Expand Down Expand Up @@ -324,7 +323,6 @@ fig.update_layout(title_text="Apple Stock Price")
fig.show()
```


### Axis lines: grid and zerolines

##### Toggling Axis grid lines
Expand Down Expand Up @@ -534,7 +532,6 @@ fig.update_yaxes(range=[3, 9])
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.
Expand Down Expand Up @@ -593,7 +590,7 @@ fig.show()

##### Decreasing the domain spanned by an axis

In the example below, the x and y axis are anchored together, and the range of the `xaxis` is set manually. By default, plotly extends the range of the axis (overriding the `range` parameter) to fit in the figure `domain`. You can restrict the `domain` to force the axis to span only the set range, by setting `constrain='domain'` as below.
In the example below, the x and y axis are anchored together, and the range of the `xaxis` is set manually. By default, plotly extends the range of the axis (overriding the `range` parameter) to fit in the figure `domain`. You can restrict the `domain` to force the axis to span only the set range, by setting `constrain='domain'` as below.

```python
import plotly.graph_objects as go
Expand Down Expand Up @@ -687,7 +684,7 @@ fig.show()

### Axis range for log axis type

If you are using a `log` type of axis and you want to set the range of the axis, you have to give the `log10` value of the bounds when using `fig.update_xaxes` or `fig.update_layout`. However, with `plotly.express` functions you pass directly the values of the range bounds (`plotly.express` then computes the appropriate values to pass to the figure layout).
If you are using a `log` type of axis and you want to set the range of the axis, you have to give the `log10` value of the bounds when using `fig.update_xaxes` or `fig.update_layout`. However, with `plotly.express` functions you pass directly the values of the range bounds (`plotly.express` then computes the appropriate values to pass to the figure layout).

```python
import plotly.express as px
Expand Down
4 changes: 4 additions & 0 deletions doc/python/bubble-maps.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ jupyter:
thumbnail: thumbnail/bubble-map.jpg
---

#### Base Map Configuration

Plotly figures made with `px.scatter_geo`, `px.line_geo` or `px.choropleth` functions or containing `go.Choropleth` or `go.Scattergeo` graph objects have a `go.layout.Geo` object which can be used to [control the appearance of the base map](/python/map-configuration/) onto which data is plotted.

### 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.
Expand Down
169 changes: 163 additions & 6 deletions doc/python/choropleth-maps.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,22 @@ jupyter:
text_representation:
extension: .md
format_name: markdown
format_version: "1.1"
jupytext_version: 1.1.1
format_version: '1.2'
jupytext_version: 1.3.1
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.6.8
plotly:
description: How to make choropleth maps in Python with Plotly.
display_as: maps
Expand All @@ -23,14 +33,152 @@ jupyter:
thumbnail: thumbnail/choropleth.jpg
---

A [Choropleth Map](https://en.wikipedia.org/wiki/Choropleth_map) is a heatmap using geographical boundaries. It is used to represent spatial variations of a quantity. See also the [index of other geographical charts](/python/maps/).
A [Choropleth Map](https://en.wikipedia.org/wiki/Choropleth_map) is a map composed of colored polygons. It is used to represent spatial variations of a quantity. This page documents how to build **outline** choropleth maps, but you can also build [choropleth **tile maps** using our Mapbox trace types](/python/mapbox-county-choropleth).

Below we show how to create Choropleth Maps using either Plotly Express' `px.choropleth` or the lower-level `go.Choropleth`.
Below we show how to create Choropleth Maps using either Plotly Express' `px.choropleth` function or the lower-level `go.Choropleth` graph object.

#### Base Map Configuration

Plotly figures made with `px.scatter_geo`, `px.line_geo` or `px.choropleth` functions or containing `go.Choropleth` or `go.Scattergeo` graph objects have a `go.layout.Geo` object which can be used to [control the appearance of the base map](/python/map-configuration/) onto which data is plotted.

### Introduction: main parameters for choropleth outline maps

Making choropleth maps requires two main types of input:

1. Geometry information:
1. This can either be a supplied GeoJSON file where each feature has either an `id` field or some identifying value in `properties`; or
2. one of the built-in geometries within `plotly`: US states and world countries (see below)
2. A list of values indexed by feature identifier.

The GeoJSON data is passed to the `geojson` argument, and the data is passed into the `color` argument of `px.choropleth_mapbox` (`z` if using `graph_objects`), in the same order as the IDs are passed into the `location` argument.

**Note** the `geojson` attribute can also be the URL to a GeoJSON file, which can speed up map rendering in certain cases.

### Choropleth 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/).

#### GeoJSON with `feature.id`

Here we load a GeoJSON file containing the geometry information for US counties, where `feature.id` is a [FIPS code](https://en.wikipedia.org/wiki/FIPS_county_code).

```python
from urllib.request import urlopen
import json
with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
counties = json.load(response)

counties["features"][0]
```

#### Data indexed by `id`

Here we load unemployment data by county, also indexed by [FIPS code](https://en.wikipedia.org/wiki/FIPS_county_code).

```python
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv",
dtype={"fips": str})
df.head()
```

### Choropleth map using GeoJSON

**Note** In this example we set `layout.geo.scope` to `usa` to automatically configure the map to display USA-centric data in an appropriate projection. See the [Geo map configuration documentation](/python/map-configuration/) for more information on scopes.

```python
from urllib.request import urlopen
import json
with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
counties = json.load(response)

import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv",
dtype={"fips": str})

import plotly.express as px

fig = px.choropleth(df, geojson=counties, locations='fips', color='unemp',
color_continuous_scale="Viridis",
range_color=(0, 12),
scope="usa",
labels={'unemp':'unemployment rate'}
)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()
```

### Indexing by GeoJSON Properties

If the GeoJSON you are using either does not have an `id` field or you wish you use one of the keys in the `properties` field, you may use the `featureidkey` parameter to specify where to match the values of `locations`.

In the following GeoJSON object/data-file pairing, the values of `properties.district` match the values of the `district` column:

```python
import plotly.express as px

df = px.data.election()
geojson = px.data.election_geojson()

print(df["district"][2])
print(geojson["features"][0]["properties"])
```

To use them together, we set `locations` to `district` and `featureidkey` to `"properties.district"`. The `color` is set to the number of votes by the candidate named Bergeron.

**Note** In this example we set `layout.geo.visible` to `False` to hide the base map and frame, and we set `layout.geo.fitbounds` to `'locations'` to automatically zoom the map to show just the area of interest. See the [Geo map configuration documentation](/python/map-configuration/) for more information on projections and bounds.

```python
import plotly.express as px

df = px.data.election()
geojson = px.data.election_geojson()

fig = px.choropleth(df, geojson=geojson, color="Bergeron",
locations="district", featureidkey="properties.district",
projection="mercator"
)
fig.update_geos(fitbounds="locations", visible=False)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()
```

### Discrete Colors

In addition to [continuous colors](/python/colorscales/), we can [discretely-color](/python/discrete-color/) our choropleth maps by setting `color` to a non-numerical column, like the name of the winner of an election.

**Note** In this example we set `layout.geo.visible` to `False` to hide the base map and frame, and we set `layout.geo.fitbounds` to `'locations'` to automatically zoom the map to show just the area of interest. See the [Geo map configuration documentation](/python/map-configuration/) for more information on projections and bounds.

```python
import plotly.express as px

df = px.data.election()
geojson = px.data.election_geojson()

fig = px.choropleth(df, geojson=geojson, color="winner",
locations="district", featureidkey="properties.district",
projection="mercator", hover_data=["Bergeron", "Coderre", "Joly"]
)
fig.update_geos(fitbounds="locations", visible=False)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()
```

<!-- #region -->
### Using Built-in Country and State Geometries

Plotly comes with two built-in geometries which do not require an external GeoJSON file:
1. USA States
2. Countries as defined in the Natural Earth dataset.


**Note and disclaimer:** cultural (as opposed to physical) features are by definition subject to change, debate and dispute. Plotly includes data from Natural Earth "as-is" and defers to the [Natural Earth policy regarding disputed borders](https://www.naturalearthdata.com/downloads/50m-cultural-vectors/50m-admin-0-countries-2/) which read:

> Natural Earth Vector draws boundaries of countries according to defacto status. We show who actually controls the situation on the ground.

To use the built-in countries geometry, provide `locations` as [three-letter ISO country codes](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3).
<!-- #endregion -->

```python
import plotly.express as px

Expand All @@ -42,6 +190,15 @@ fig = px.choropleth(df, locations="iso_alpha",
fig.show()
```

To use the USA States geometry, set `locationmode='USA-states'` and provide `locations` as two-letter state abbreviations:

```python
import plotly.express as px

fig = px.choropleth(locations=["CA", "TX", "NY"], locationmode="USA-states", color=[1,2,3], scope="usa")
fig.show()
```

### Choropleth Maps with go.Choropleth

#### United States Choropleth Map
Expand Down Expand Up @@ -238,9 +395,9 @@ HDX</a>',
fig.show()
```

#### Full County Choropleths
#### County Choropleth Figure Factory

For the full county choropleth doc page checkout https://plot.ly/python/county-choropleth/
Plotly also includes a [legacy "figure factory" for creating US county-level choropleth maps](python/county-choropleth/).

```python
import plotly.figure_factory as ff
Expand Down
16 changes: 11 additions & 5 deletions doc/python/county-choropleth.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ jupyter:
text_representation:
extension: .md
format_name: markdown
format_version: '1.1'
jupytext_version: 1.1.1
format_version: '1.2'
jupytext_version: 1.3.1
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.3
version: 3.6.8
plotly:
description: How to create colormaped representations of USA counties by FIPS
values in Python.
Expand All @@ -34,6 +34,12 @@ jupyter:
thumbnail: thumbnail/county-choropleth-usa-greybkgd.jpg
---

### Deprecation warning


This page describes a legacy "figure factory" method for creating map-like figures using [self-filled scatter traces](/python/shapes). **This is no longer the recommended way to make county-level choropleth maps**, instead we recommend using a [GeoJSON-based approach to making outline choropleth maps](/python/choropleth-maps/) or the alternative [Mapbox tile-based choropleth maps](/python/mapbox-county-choropleth).


#### Required Packages
`geopandas`, `pyshp` and `shapely` must be installed for this figure factory.

Expand All @@ -47,10 +53,10 @@ Run the following commands to install the correct versions of the following modu

If you are using Windows, follow this post to properly install geopandas and dependencies: http://geoffboeing.com/2014/09/using-geopandas-windows/. If you are using Anaconda, do not use PIP to install the packages above. Instead use conda to install them:

```
<!-- #raw -->
conda install plotly
conda install geopandas
```
<!-- #endraw -->

#### FIPS and Values
Every US state and county has an assined ID regulated by the US Federal Government under the term FIPS (Federal Information Processing Standards) codes. There are state codes and county codes: the 2016 state and county FIPS codes can be found at the [US Census Website](https://www.census.gov/geographies/reference-files/2016/demo/popest/2016-fips.html).
Expand Down
Loading