Skip to content

Commit 7177840

Browse files
authored
Merge pull request #138 from plotly/_treemap_python
Treemap python
2 parents 2629984 + 2fd565e commit 7177840

File tree

2 files changed

+154
-71
lines changed

2 files changed

+154
-71
lines changed

python/treemaps.md

Lines changed: 153 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ jupyter:
66
extension: .md
77
format_name: markdown
88
format_version: '1.1'
9-
jupytext_version: 1.1.1
9+
jupytext_version: 1.2.1
1010
kernelspec:
1111
display_name: Python 3
1212
language: python
@@ -20,93 +20,176 @@ jupyter:
2020
name: python
2121
nbconvert_exporter: python
2222
pygments_lexer: ipython3
23-
version: 3.6.7
23+
version: 3.7.3
2424
plotly:
25-
description: How to make interactive treemap in Python with Plotly and Squarify.
26-
An examples of a treemap in Plotly using Squarify.
27-
display_as: statistical
25+
description: How to make Treemap Charts with Plotly
26+
display_as: basic
2827
has_thumbnail: true
29-
ipynb: ~notebook_demo/29
28+
ipynb: ~notebook_demo/280/
3029
language: python
3130
layout: base
32-
name: Treemaps
33-
order: 11
31+
name: Treemap Charts
32+
order: 14
3433
page_type: u-guide
3534
permalink: python/treemaps/
36-
thumbnail: thumbnail/treemap.jpg
37-
title: Python Treemaps | plotly
38-
v4upgrade: true
35+
thumbnail: thumbnail/treemap.png
36+
title: Treemap in Python | plotly
3937
---
4038

41-
#### Simple Example with Plotly and [Squarify](https://pypi.python.org/pypi/squarify)
42-
Define the coordinate system for the returned rectangles: these values will range from x to x + width and y to y + height.
43-
Then define your treemap values. The sum of the treemap values must equal the total area to be laid out (i.e. width `*` height). The values must be sorted in descending order and must be positive.
39+
### Basic Treemap
40+
41+
[Treemap charts](https://en.wikipedia.org/wiki/Treemapping) visualize hierarchical data using nested rectangles. Same as [Sunburst](https://plot.ly/python/sunburst-charts/) the hierarchy is defined by [labels](https://plot.ly/python/reference/#treemap-labels) and [parents]((https://plot.ly/python/reference/#treemap-parents)) attributes. Click on one sector to zoom in/out, which also displays a pathbar in the upper-left corner of your treemap. To zoom out you can use the path bar as well.
4442

4543
```python
4644
import plotly.graph_objects as go
4745

48-
import squarify
49-
50-
fig = go.Figure()
51-
52-
x = 0.
53-
y = 0.
54-
width = 100.
55-
height = 100.
56-
57-
values = [500, 433, 78, 25, 25, 7]
58-
59-
normed = squarify.normalize_sizes(values, width, height)
60-
rects = squarify.squarify(normed, x, y, width, height)
61-
62-
# Choose colors from http://colorbrewer2.org/ under "Export"
63-
color_brewer = ['rgb(166,206,227)','rgb(31,120,180)','rgb(178,223,138)',
64-
'rgb(51,160,44)','rgb(251,154,153)','rgb(227,26,28)']
65-
shapes = []
66-
annotations = []
67-
counter = 0
68-
69-
for r, val, color in zip(rects, values, color_brewer):
70-
shapes.append(
71-
dict(
72-
type = 'rect',
73-
x0 = r['x'],
74-
y0 = r['y'],
75-
x1 = r['x']+r['dx'],
76-
y1 = r['y']+r['dy'],
77-
line = dict( width = 2 ),
78-
fillcolor = color
79-
)
80-
)
81-
annotations.append(
82-
dict(
83-
x = r['x']+(r['dx']/2),
84-
y = r['y']+(r['dy']/2),
85-
text = val,
86-
showarrow = False
87-
)
88-
)
89-
90-
# For hover text
91-
fig.add_trace(go.Scatter(
92-
x = [ r['x']+(r['dx']/2) for r in rects ],
93-
y = [ r['y']+(r['dy']/2) for r in rects ],
94-
text = [ str(v) for v in values ],
95-
mode = 'text',
46+
fig = go.Figure(go.Treemap(
47+
labels = ["Eve","Cain", "Seth", "Enos", "Noam", "Abel", "Awan", "Enoch", "Azura"],
48+
parents = ["", "Eve", "Eve", "Seth", "Seth", "Eve", "Eve", "Awan", "Eve"]
9649
))
9750

51+
fig.show()
52+
```
53+
54+
### Set Different Attributes in Treemap
55+
56+
This example uses the following attributes:
57+
58+
1. [values](https://plot.ly/python/reference/#treemap-values): sets the values associated with each of the sectors.
59+
2. [textinfo](https://plot.ly/python/reference/#treemap-textinfo): determines which trace information appear on the graph that can be 'text', 'value', 'current path', 'percent root', 'percent entry', and 'percent parent', or any combination of them.
60+
3. [pathbar](https://plot.ly/python/reference/#treemap-pathbar): a main extra feature of treemap to display the current path of the visible portion of the hierarchical map. It may also be useful for zooming out of the graph.
61+
4. [branchvalues](https://plot.ly/python/reference/#treemap-branchvalues): determines how the items in `values` are summed. When set to "total", items in `values` are taken to be value of all its descendants. In the example below Eva = 65, which is equal to 14 + 12 + 10 + 2 + 6 + 6 + 1 + 4.
62+
When set to "remainder", items in `values` corresponding to the root and the branches sectors are taken to be the extra part not part of the sum of the values at their leaves.
63+
64+
```python
65+
import plotly.graph_objects as go
66+
from plotly.subplots import make_subplots
67+
68+
labels = ["Eve", "Cain", "Seth", "Enos", "Noam", "Abel", "Awan", "Enoch", "Azura"]
69+
parents = ["", "Eve", "Eve", "Seth", "Seth", "Eve", "Eve", "Awan", "Eve"]
70+
71+
fig = make_subplots(
72+
cols = 2, rows = 1,
73+
column_widths = [0.4, 0.4],
74+
subplot_titles = ('branchvalues: <b>remainder<br />&nbsp;<br />', 'branchvalues: <b>total<br />&nbsp;<br />'),
75+
specs = [[{'type': 'treemap', 'rowspan': 1}, {'type': 'treemap'}]]
76+
)
77+
78+
fig.add_trace(go.Treemap(
79+
labels = labels,
80+
parents = parents,
81+
values = [10, 14, 12, 10, 2, 6, 6, 1, 4],
82+
textinfo = "label+value+percent parent+percent entry+percent root",
83+
),
84+
row = 1, col = 1)
85+
86+
fig.add_trace(go.Treemap(
87+
branchvalues = "total",
88+
labels = labels,
89+
parents = parents,
90+
values = [65, 14, 12, 10, 2, 6, 6, 1, 4],
91+
textinfo = "label+value+percent parent+percent entry",
92+
outsidetextfont = {"size": 20, "color": "darkblue"},
93+
marker = {"line": {"width": 2}},
94+
pathbar = {"visible": False}),
95+
row = 1, col = 2)
96+
97+
fig.show()
98+
```
99+
100+
### Set Color of Treemap Sectors
101+
102+
There are three different ways to change the color of the sectors in Treemap:
103+
1) [marker.colors](https://plot.ly/javascript/reference/#treemap-marker-colors), 2) [colorway](https://plot.ly/javascript/reference/#treemap-colorway), 3) [colorscale](https://plot.ly/javascript/reference/#treemap-colorscale). The following examples show how to use each of them.
104+
105+
```python
106+
import plotly.graph_objects as go
107+
108+
labels = ["A1", "A2", "A3", "A4", "A5", "B1", "B2"]
109+
parents = ["", "A1", "A2", "A3", "A4", "", "B1"]
110+
111+
fig = go.Figure(go.Treemap(
112+
labels = labels,
113+
parents = parents,
114+
marker_colors = ["pink", "royalblue", "lightgray", "purple", "cyan", "lightgray", "lightblue"]))
115+
116+
fig.show()
117+
```
118+
119+
This example uses `treemapcolorway` attribute, which should be set in layout.
120+
121+
```python
122+
import plotly.graph_objects as go
123+
124+
labels = ["A1", "A2", "A3", "A4", "A5", "B1", "B2"]
125+
parents = ["", "A1", "A2", "A3", "A4", "", "B1"]
126+
127+
fig = go.Figure(go.Treemap(
128+
labels = labels,
129+
parents = parents
130+
))
131+
132+
fig.update_layout(treemapcolorway = ["pink", "lightgray"])
133+
134+
fig.show()
135+
```
136+
137+
```python
138+
import plotly.graph_objects as go
139+
140+
values = ["11", "12", "13", "14", "15", "20", "30"]
141+
labels = ["A1", "A2", "A3", "A4", "A5", "B1", "B2"]
142+
parents = ["", "A1", "A2", "A3", "A4", "", "B1"]
143+
144+
fig = go.Figure(go.Treemap(
145+
labels = labels,
146+
values = values,
147+
parents = parents,
148+
marker_colorscale = 'Blues'))
149+
150+
fig.show()
151+
```
152+
153+
### Nested Layers in Treemap
154+
155+
The following example uses hierarchical data that includes layers and grouping. Treemap and [Sunburst](https://plot.ly/python/sunburst-charts/) charts reveal insights into the data, and the format of your hierarchical data. [maxdepth](https://plot.ly/python/reference/#treemap-maxdepth) attribute sets the number of rendered sectors from the given level.
156+
157+
```python
158+
import plotly.graph_objects as go
159+
from plotly.subplots import make_subplots
160+
161+
import pandas as pd
162+
163+
df1 = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/718417069ead87650b90472464c7565dc8c2cb1c/sunburst-coffee-flavors-complete.csv')
164+
df2 = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/718417069ead87650b90472464c7565dc8c2cb1c/coffee-flavors.csv')
165+
166+
fig = make_subplots(
167+
rows = 1, cols = 2,
168+
column_widths = [0.4, 0.4],
169+
specs = [[{'type': 'treemap', 'rowspan': 1}, {'type': 'treemap'}]]
170+
)
171+
172+
fig.add_trace(
173+
go.Treemap(
174+
ids = df1.ids,
175+
labels = df1.labels,
176+
parents = df1.parents),
177+
col = 1, row = 1)
178+
179+
fig.add_trace(
180+
go.Treemap(
181+
ids = df2.ids,
182+
labels = df2.labels,
183+
parents = df2.parents,
184+
maxdepth = 3),
185+
col = 2, row = 1)
186+
98187
fig.update_layout(
99-
height=700,
100-
width=700,
101-
xaxis=dict(showgrid=False,zeroline=False),
102-
yaxis=dict(showgrid=False,zeroline=False),
103-
shapes=shapes,
104-
annotations=annotations,
105-
hovermode='closest'
188+
margin = {'t':0, 'l':0, 'r':0, 'b':0}
106189
)
107190

108191
fig.show()
109192
```
110193

111194
#### Reference
112-
See https://plot.ly/python/reference/ for more information and chart attribute options or https://pypi.python.org/pypi/squarify for more information about squarify!
195+
See https://plot.ly/python/reference/#treemap for more information and chart attribute options!

requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
plotly==4.1.1
1+
plotly==4.2.0
22
jupytext==1.1.1
33
jupyter
44
notebook

0 commit comments

Comments
 (0)