Skip to content

Commit a291b6f

Browse files
revamp continuous color docs, add categorical color docs
1 parent 3ce7998 commit a291b6f

File tree

3 files changed

+455
-28
lines changed

3 files changed

+455
-28
lines changed

Diff for: doc/python/builtin-colorscales.md

+15-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ jupyter:
3636
v4upgrade: true
3737
---
3838

39-
### Using Built-In Colorscales
39+
### Using Built-In Continuous Colorscales
4040

4141
Many Plotly Express functions accept a `color_continuous_scale` argument and many trace
4242
types have a `colorscale` attribute in their schema. Plotly comes with a large number of
@@ -49,6 +49,12 @@ The `plotly.colours` module is also available under `plotly.express.colors` so y
4949

5050
When using continuous colorscales, you will often want to [configure various aspects of its range and colorbar](/python/colorscales/).
5151

52+
53+
### Categorical Color Sequences
54+
55+
Plotly also comes with some built-in [categorical color sequences](/python/categorical-color/) which are *not intended* to be used with the `color_continuous_scale` argument as they are not designed for interpolation to occur between adjacent colors.
56+
57+
5258
### Named Built-In Colorscales
5359

5460
You can use any of the following names as string values to set `continuous_color_scale` or `colorscale` arguments.
@@ -62,6 +68,14 @@ named_colorscales = px.colors.named_colorscales()
6268
print("\n".join(wrap("".join('{:<12}'.format(c) for c in named_colorscales), 96)))
6369
```
6470

71+
Built-in color scales are stored as lists of CSS colors:
72+
73+
```python
74+
import plotly.express as px
75+
76+
print(px.colors.sequential.Plasma)
77+
```
78+
6579
### Built-In Sequential Colorscales
6680

6781
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).

Diff for: doc/python/categorical-colors.md

+233
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,233 @@
1+
---
2+
jupyter:
3+
jupytext:
4+
notebook_metadata_filter: all
5+
text_representation:
6+
extension: .md
7+
format_name: markdown
8+
format_version: '1.2'
9+
jupytext_version: 1.3.1
10+
kernelspec:
11+
display_name: Python 3
12+
language: python
13+
name: python3
14+
language_info:
15+
codemirror_mode:
16+
name: ipython
17+
version: 3
18+
file_extension: .py
19+
mimetype: text/x-python
20+
name: python
21+
nbconvert_exporter: python
22+
pygments_lexer: ipython3
23+
version: 3.6.8
24+
plotly:
25+
description: How to use and configure categorical (also known as qualitative or
26+
discrete) color sequences.
27+
display_as: file_settings
28+
has_thumbnail: true
29+
ipynb: ~notebook_demo/187
30+
language: python
31+
layout: base
32+
name: Categorical Colors
33+
order: 27
34+
permalink: python/colorscales/
35+
redirect_from: python/logarithmic-color-scale/
36+
thumbnail: thumbnail/heatmap_colorscale.jpg
37+
v4upgrade: true
38+
---
39+
40+
### Categorical vs Continuous Color
41+
42+
In the same way as the X or Y position of a mark in cartesian coordinates can be used to represent continuous values (i.e. amounts or moments in time) or categories (i.e. labels), color can be used to represent continuous or categorical data. This page is about using color to represent **categorical** data, but Plotly can also [represent continuous values with color](/python/colorscales/).
43+
44+
45+
### Categorical Color Concepts
46+
47+
This document explains the following categorical-color-related concepts:
48+
49+
- **color sequences** are lists of colors to be mapped onto discrete data values. No interpolation occurs when using color sequences, unlike with [continuous color scales](/python/colorscales/), and each color is used as-is. Color sequence defaults depend on the `layout.colorway` attribute of the active [template](/python/templates/), and can be explicitly specified using the `color_discrete_sequence` argument for many [Plotly Express](/python/plotly-express/) functions.
50+
- **legends** are visible representations of the mapping between colors and data values. Legend markers also change shape when used with various kinds of traces, such as symbols or lines for scatter-like traces. [Legends are configurable](/python/legend/) under the `layout.legend` attribute. Legends are the categorical equivalent of [continous color bars](/python/colorscales/)
51+
52+
53+
### Categorical Color with Plotly Express
54+
55+
Most Plotly Express functions accept a `color` argument which automatically assigns data values to categorical colors **if the data is non-numeric**. If the data is numeric, the color will automatically be considered [continuous](/python/colorscales/). This means that numeric strings must be parsed to be used for continuous color, and conversely, numbers used as category codes must be converted to strings.
56+
57+
For example, in the `tips` dataset, the `smoker` column contains strings:
58+
59+
```python
60+
import plotly.express as px
61+
df = px.data.tips()
62+
fig = px.scatter(df, x="total_bill", y="tip", color="smoker", title="String 'smoker' values mean categorical colors")
63+
64+
fig.show()
65+
```
66+
67+
The `size` column, however, contains numbers:
68+
69+
```python
70+
import plotly.express as px
71+
df = px.data.tips()
72+
fig = px.scatter(df, x="total_bill", y="tip", color="size", title="Numeric 'size' values mean continous color")
73+
74+
fig.show()
75+
```
76+
77+
Converting this column to strings is very straightforward, but note that the ordering in the legend is not sequential by default (see below for how to control categorical order):
78+
79+
```python
80+
import plotly.express as px
81+
df = px.data.tips()
82+
df["size"] = df["size"].astype(str)
83+
fig = px.scatter(df, x="total_bill", y="tip", color="size", title="String 'size' values mean categorical colors")
84+
85+
fig.show()
86+
```
87+
88+
Converting a string column to a numeric one is also quite straightforward:
89+
90+
```python
91+
import plotly.express as px
92+
df = px.data.tips()
93+
df["size"] = df["size"].astype(str) #convert to string
94+
df["size"] = df["size"].astype(float) #convert back to numeric
95+
96+
fig = px.scatter(df, x="total_bill", y="tip", color="size", title="Numeric 'size' values mean continous color")
97+
98+
fig.show()
99+
```
100+
101+
### Color Sequences in Plotly Express
102+
103+
By default, Plotly Express will use the color sequence from the active [template](/python/templates/)'s `layout.colorway` attribute, and the default active template is `plotly` which uses the `plotly` color sequence. You can choose any of the following built-in qualitative color sequences from the `px.colors.qualitative` module, however, or define your own.
104+
105+
```python
106+
import plotly.express as px
107+
108+
fig = px.colors.qualitative.swatches()
109+
fig.show()
110+
```
111+
112+
Color sequences in the `px.colors.qualitative` module are stored as lists of CSS colors:
113+
114+
```python
115+
import plotly.express as px
116+
117+
print(px.colors.qualitative.Plotly)
118+
```
119+
120+
Here is an example that creates a scatter plot using Plotly Express, with points colored using the built-in qualitative `G10` color sequence.
121+
122+
```python
123+
import plotly.express as px
124+
df = px.data.gapminder()
125+
fig = px.line(df, y="lifeExp", x="year", color="continent", line_group="country",
126+
line_shape="spline", render_mode="svg",
127+
color_discrete_sequence=px.colors.qualitative.G10,
128+
title="Built-in G10 color sequence")
129+
130+
fig.show()
131+
```
132+
133+
### Explicity Constructing a Color Sequence
134+
135+
The Plotly Express `color_discrete_sequence` argument accepts explicitly-constructed color sequences as well, as lists of CSS colors:
136+
137+
```python
138+
import plotly.express as px
139+
df = px.data.gapminder().query("year == 2007")
140+
fig = px.bar(df, y="continent", x="pop", color="continent", orientation="h", hover_name="country",
141+
color_discrete_sequence=["red", "green", "blue", "goldenrod", "magenta"],
142+
title="Explicit color sequence"
143+
)
144+
145+
fig.show()
146+
```
147+
148+
***Warning***: If your color sequence is has fewer colors than the number of unique values in the column you are mapping to `color`, the colors will cycle through and repeat, possibly leading to ambiguity:
149+
150+
```python
151+
import plotly.express as px
152+
df = px.data.tips()
153+
fig = px.scatter(df, x="total_bill", y="tip", color="day",
154+
color_discrete_sequence=["red", "blue"],
155+
title="<b>Ambiguous!</b> Explicit color sequence cycling because it is too short"
156+
)
157+
158+
fig.show()
159+
```
160+
161+
### Directly Mapping Colors to Data Values
162+
163+
The example above assigned colors to data values on a first-come-first-served basis, but you can directly map colors to data values if this is important to your application with `color_discrete_map`. Note that this does not change the order in which values appear in the figure or legend, as can be controlled below:
164+
165+
```python
166+
import plotly.express as px
167+
df = px.data.gapminder().query("year == 2007")
168+
fig = px.bar(df, y="continent", x="pop", color="continent", orientation="h", hover_name="country",
169+
color_discrete_map={
170+
"Europe": "red",
171+
"Asia": "green",
172+
"Americas": "blue",
173+
"Oceania": "goldenrod",
174+
"Africa": "magenta"},
175+
title="Explicit color mapping")
176+
177+
fig.show()
178+
```
179+
180+
### Controlling Categorical Order
181+
182+
Plotly Express lets you specify an ordering over categorical variables with `category_orders`, which will apply to colors and legends as well as symbols, [axes](/python/axes/) and [facets](/python/facet-plots/). This can be used with either `color_discrete_sequence` or `color_discrete_map`.
183+
184+
```python
185+
import plotly.express as px
186+
df = px.data.gapminder().query("year == 2007")
187+
fig = px.bar(df, y="continent", x="pop", color="continent", orientation="h", hover_name="country",
188+
color_discrete_map={
189+
"Europe": "red",
190+
"Asia": "green",
191+
"Americas": "blue",
192+
"Oceania": "goldenrod",
193+
"Africa": "magenta"},
194+
category_orders={"continent": ["Oceania", "Europe", "Asia", "Africa", "Americas"]},
195+
title="Explicit color sequence with explicit ordering"
196+
)
197+
198+
fig.show()
199+
```
200+
201+
```python
202+
import plotly.express as px
203+
df = px.data.gapminder().query("year == 2007")
204+
fig = px.bar(df, y="continent", x="pop", color="continent", orientation="h", hover_name="country",
205+
color_discrete_sequence=["red", "green", "blue", "goldenrod", "magenta"],
206+
category_orders={"continent": ["Oceania", "Europe", "Asia", "Africa", "Americas"]},
207+
title="Explicit color mapping with explicit ordering"
208+
)
209+
210+
fig.show()
211+
```
212+
213+
### Using Sequential Scales as Categorical Sequences
214+
215+
In most cases, discrete/qualitative/categorical data values have no meaningful natural ordering, such as in the continents example used above. In some cases, however, there is a meaningful order, and in this case it can be helpful and appealing to use part of a continuous scale as a categorical sequence, as in the following [wind rose chart](/python/wind-rose-charts/):
216+
217+
```python
218+
import plotly.express as px
219+
df = px.data.wind()
220+
fig = px.bar_polar(df, r="frequency", theta="direction", color="strength",
221+
color_discrete_sequence= px.colors.sequential.Plasma[-2::-1],
222+
title="Part of a continuous color scale used as a discrete sequence"
223+
)
224+
fig.show()
225+
```
226+
227+
This works because just like in `px.colors.qualitative`, all [built-in continuous color scales](/python/builtin-colorscales/) are stored as lists of CSS colors:
228+
229+
```python
230+
import plotly.express as px
231+
232+
print(px.colors.sequential.Plasma)
233+
```

0 commit comments

Comments
 (0)