plotify-charts 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- plotify/__init__.py +116 -0
- plotify/_inference.py +144 -0
- plotify/auto.py +360 -0
- plotify/base.py +224 -0
- plotify/categorical/__init__.py +37 -0
- plotify/categorical/bar_plot.py +121 -0
- plotify/categorical/circular_packing.py +107 -0
- plotify/categorical/dendrogram.py +113 -0
- plotify/categorical/doughnut_chart.py +109 -0
- plotify/categorical/lollipop_chart.py +168 -0
- plotify/categorical/parallel_coordinates.py +94 -0
- plotify/categorical/pie_chart.py +101 -0
- plotify/categorical/radar_chart.py +116 -0
- plotify/categorical/sunburst_diagram.py +117 -0
- plotify/categorical/treemap.py +121 -0
- plotify/categorical/venn_diagram.py +92 -0
- plotify/categorical/word_cloud.py +104 -0
- plotify/maps/__init__.py +21 -0
- plotify/maps/bubble_map.py +114 -0
- plotify/maps/cartogram.py +126 -0
- plotify/maps/choropleth_map.py +108 -0
- plotify/maps/connection_map.py +117 -0
- plotify/maps/hexbin_map.py +96 -0
- plotify/network/__init__.py +21 -0
- plotify/network/arc_diagram.py +124 -0
- plotify/network/chord_diagram.py +119 -0
- plotify/network/hierarchical_edge_bundling.py +141 -0
- plotify/network/network_diagram.py +167 -0
- plotify/network/sankey_diagram.py +258 -0
- plotify/num_cat/__init__.py +19 -0
- plotify/num_cat/box_plot_by_group.py +110 -0
- plotify/num_cat/grouped_bar_plot.py +110 -0
- plotify/num_cat/grouped_scatter.py +105 -0
- plotify/num_cat/stacked_bar_plot.py +117 -0
- plotify/numerical/__init__.py +21 -0
- plotify/numerical/boxplot.py +157 -0
- plotify/numerical/connected_scatter_plot.py +120 -0
- plotify/numerical/density_plot.py +184 -0
- plotify/numerical/scatter_plot.py +140 -0
- plotify/numerical/violin_plot.py +141 -0
- plotify/theme.py +297 -0
- plotify/timeseries/__init__.py +13 -0
- plotify/timeseries/area_chart.py +89 -0
- plotify/timeseries/line_chart.py +110 -0
- plotify/timeseries/stacked_area_chart.py +133 -0
- plotify/timeseries/stream_graph.py +116 -0
- plotify_charts-0.1.0.dist-info/LICENSE +21 -0
- plotify_charts-0.1.0.dist-info/METADATA +226 -0
- plotify_charts-0.1.0.dist-info/RECORD +50 -0
- plotify_charts-0.1.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""
|
|
2
|
+
plotify.categorical.treemap
|
|
3
|
+
===========================
|
|
4
|
+
|
|
5
|
+
Treemap — nested rectangles whose areas are proportional to a numeric
|
|
6
|
+
variable.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import matplotlib.pyplot as plt
|
|
10
|
+
import plotly.express as px
|
|
11
|
+
import squarify
|
|
12
|
+
|
|
13
|
+
from plotify.base import BasePlot
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Treemap(BasePlot):
|
|
17
|
+
"""
|
|
18
|
+
Treemap.
|
|
19
|
+
|
|
20
|
+
Seaborn backend builds the layout with :mod:`squarify` and renders via
|
|
21
|
+
Matplotlib. Plotly backend uses :func:`plotly.express.treemap`, which
|
|
22
|
+
supports nested hierarchies directly.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
df,
|
|
28
|
+
labels,
|
|
29
|
+
values,
|
|
30
|
+
parents=None,
|
|
31
|
+
color=None,
|
|
32
|
+
palette=None,
|
|
33
|
+
title=None,
|
|
34
|
+
backend="seaborn",
|
|
35
|
+
**kwargs,
|
|
36
|
+
):
|
|
37
|
+
"""
|
|
38
|
+
This is used to create a treemap.
|
|
39
|
+
|
|
40
|
+
Parameters
|
|
41
|
+
----------
|
|
42
|
+
df : pandas.DataFrame
|
|
43
|
+
Input data.
|
|
44
|
+
labels : str
|
|
45
|
+
Column containing rectangle labels.
|
|
46
|
+
values : str
|
|
47
|
+
Column containing numeric values (drive rectangle area).
|
|
48
|
+
parents : str, optional
|
|
49
|
+
Column with parent-label references for hierarchical treemaps.
|
|
50
|
+
Seaborn backend ignores this (squarify is flat); Plotly backend
|
|
51
|
+
uses it to build the hierarchy.
|
|
52
|
+
color : str, optional
|
|
53
|
+
Column name used to colour-encode rectangles (Plotly only).
|
|
54
|
+
palette : list[str], optional
|
|
55
|
+
Seaborn colours for the rectangles.
|
|
56
|
+
title : str, optional
|
|
57
|
+
Plot title.
|
|
58
|
+
backend : {"seaborn", "plotly"}, default="seaborn"
|
|
59
|
+
Rendering backend.
|
|
60
|
+
**kwargs :
|
|
61
|
+
Forwarded to the underlying library.
|
|
62
|
+
|
|
63
|
+
Returns
|
|
64
|
+
-------
|
|
65
|
+
None
|
|
66
|
+
"""
|
|
67
|
+
self.__df = df
|
|
68
|
+
self.__labels = labels
|
|
69
|
+
self.__values = values
|
|
70
|
+
self.__parents = parents
|
|
71
|
+
self.__color = color
|
|
72
|
+
self.__palette = palette
|
|
73
|
+
self.__kwargs = kwargs
|
|
74
|
+
|
|
75
|
+
super().__init__(backend=backend, title=title)
|
|
76
|
+
self._render()
|
|
77
|
+
|
|
78
|
+
def _plot_seaborn(self):
|
|
79
|
+
"""Render a flat treemap with :mod:`squarify`."""
|
|
80
|
+
values = self.__df[self.__values].tolist()
|
|
81
|
+
labels = self.__df[self.__labels].tolist()
|
|
82
|
+
squarify.plot(
|
|
83
|
+
sizes=values,
|
|
84
|
+
label=labels,
|
|
85
|
+
color=self.__palette,
|
|
86
|
+
**self.__kwargs,
|
|
87
|
+
)
|
|
88
|
+
plt.axis("off") # rectangles carry all the information
|
|
89
|
+
if self._title:
|
|
90
|
+
plt.title(self._title)
|
|
91
|
+
|
|
92
|
+
def _plot_plotly(self):
|
|
93
|
+
"""Render using :func:`plotly.express.treemap`.
|
|
94
|
+
|
|
95
|
+
When a ``parents`` column is supplied we use Plotly Express's
|
|
96
|
+
``path=`` form, which builds the parent → leaf hierarchy
|
|
97
|
+
automatically and aggregates values. Without ``parents`` we fall
|
|
98
|
+
back to a flat treemap with every label as a top-level node.
|
|
99
|
+
"""
|
|
100
|
+
if self.__parents:
|
|
101
|
+
# Hierarchical: let Plotly Express handle the parent chain.
|
|
102
|
+
# Passing path=[parent_col, leaf_col] aggregates values by
|
|
103
|
+
# parent automatically, which is what the user expects.
|
|
104
|
+
fig = px.treemap(
|
|
105
|
+
self.__df,
|
|
106
|
+
path=[self.__parents, self.__labels],
|
|
107
|
+
values=self.__values,
|
|
108
|
+
color=self.__color,
|
|
109
|
+
title=self._title,
|
|
110
|
+
**self.__kwargs,
|
|
111
|
+
)
|
|
112
|
+
else:
|
|
113
|
+
# Flat: every leaf shares the implicit empty-string root.
|
|
114
|
+
fig = px.treemap(
|
|
115
|
+
names=self.__df[self.__labels].tolist(),
|
|
116
|
+
parents=[""] * len(self.__df),
|
|
117
|
+
values=self.__df[self.__values].tolist(),
|
|
118
|
+
title=self._title,
|
|
119
|
+
**self.__kwargs,
|
|
120
|
+
)
|
|
121
|
+
self._fig = fig
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""
|
|
2
|
+
plotify.categorical.venn_diagram
|
|
3
|
+
================================
|
|
4
|
+
|
|
5
|
+
Venn diagram — overlapping circles showing set intersections. Plotly has no
|
|
6
|
+
native Venn support, so only the Matplotlib backend (via
|
|
7
|
+
:mod:`matplotlib_venn`) is implemented.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import matplotlib.pyplot as plt
|
|
11
|
+
from matplotlib_venn import venn2, venn3
|
|
12
|
+
|
|
13
|
+
from plotify.base import BasePlot
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class VennDiagram(BasePlot):
|
|
17
|
+
"""
|
|
18
|
+
Two- or three-set Venn diagram.
|
|
19
|
+
|
|
20
|
+
Pass either two or three sets via ``sets``. Set labels are taken from
|
|
21
|
+
the ``labels`` argument (defaulting to ``("A", "B")`` or
|
|
22
|
+
``("A", "B", "C")``).
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
# matplotlib_venn has no Plotly equivalent.
|
|
26
|
+
SUPPORTED_BACKENDS = ("seaborn",)
|
|
27
|
+
|
|
28
|
+
def __init__(
|
|
29
|
+
self,
|
|
30
|
+
sets,
|
|
31
|
+
labels=None,
|
|
32
|
+
colors=None,
|
|
33
|
+
title=None,
|
|
34
|
+
backend="seaborn",
|
|
35
|
+
**kwargs,
|
|
36
|
+
):
|
|
37
|
+
"""
|
|
38
|
+
This is used to create a Venn diagram.
|
|
39
|
+
|
|
40
|
+
Parameters
|
|
41
|
+
----------
|
|
42
|
+
sets : list[set]
|
|
43
|
+
List of two or three Python :class:`set` objects.
|
|
44
|
+
labels : list[str], optional
|
|
45
|
+
Labels for the sets. Defaults to letters.
|
|
46
|
+
colors : list[str], optional
|
|
47
|
+
Fill colour per set.
|
|
48
|
+
title : str, optional
|
|
49
|
+
Plot title.
|
|
50
|
+
backend : {"seaborn"}
|
|
51
|
+
Only the Seaborn/Matplotlib backend is supported.
|
|
52
|
+
**kwargs :
|
|
53
|
+
Forwarded to :mod:`matplotlib_venn`.
|
|
54
|
+
|
|
55
|
+
Returns
|
|
56
|
+
-------
|
|
57
|
+
None
|
|
58
|
+
"""
|
|
59
|
+
if len(sets) not in (2, 3):
|
|
60
|
+
raise ValueError("matplotlib-venn supports only 2-set or 3-set Venn diagrams.")
|
|
61
|
+
|
|
62
|
+
self.__sets = [set(s) for s in sets]
|
|
63
|
+
self.__labels = labels
|
|
64
|
+
self.__colors = colors
|
|
65
|
+
self.__kwargs = kwargs
|
|
66
|
+
|
|
67
|
+
super().__init__(backend=backend, title=title)
|
|
68
|
+
self._render()
|
|
69
|
+
|
|
70
|
+
def _plot_seaborn(self):
|
|
71
|
+
"""Dispatch to ``venn2`` or ``venn3`` based on set count."""
|
|
72
|
+
n = len(self.__sets)
|
|
73
|
+
default_labels = ("A", "B", "C")[:n]
|
|
74
|
+
labels = tuple(self.__labels) if self.__labels else default_labels
|
|
75
|
+
|
|
76
|
+
if n == 2:
|
|
77
|
+
venn2(
|
|
78
|
+
subsets=self.__sets,
|
|
79
|
+
set_labels=labels,
|
|
80
|
+
set_colors=self.__colors or ("red", "blue"),
|
|
81
|
+
**self.__kwargs,
|
|
82
|
+
)
|
|
83
|
+
else:
|
|
84
|
+
venn3(
|
|
85
|
+
subsets=self.__sets,
|
|
86
|
+
set_labels=labels,
|
|
87
|
+
set_colors=self.__colors or ("red", "blue", "green"),
|
|
88
|
+
**self.__kwargs,
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
if self._title:
|
|
92
|
+
plt.title(self._title)
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""
|
|
2
|
+
plotify.categorical.word_cloud
|
|
3
|
+
==============================
|
|
4
|
+
|
|
5
|
+
Word cloud chart. Plotly has no native word cloud primitive, so only the
|
|
6
|
+
Seaborn/Matplotlib backend is implemented; asking for ``backend="plotly"``
|
|
7
|
+
raises :class:`ValueError` at construction time.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import matplotlib.pyplot as plt
|
|
11
|
+
from wordcloud import WordCloud
|
|
12
|
+
|
|
13
|
+
from plotify.base import BasePlot
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class WordCloudPlot(BasePlot):
|
|
17
|
+
"""
|
|
18
|
+
Word cloud chart.
|
|
19
|
+
|
|
20
|
+
Accepts either (a) a single string of text via ``text``, or (b) a mapping
|
|
21
|
+
of word → frequency via ``frequencies``. Exactly one must be provided.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
# Override: this class does not support the Plotly backend. The base
|
|
25
|
+
# class's __init__ will raise ValueError if the caller requests it.
|
|
26
|
+
SUPPORTED_BACKENDS = ("seaborn",)
|
|
27
|
+
|
|
28
|
+
def __init__(
|
|
29
|
+
self,
|
|
30
|
+
text=None,
|
|
31
|
+
frequencies=None,
|
|
32
|
+
width=800,
|
|
33
|
+
height=400,
|
|
34
|
+
background_color="white",
|
|
35
|
+
colormap="viridis",
|
|
36
|
+
max_words=200,
|
|
37
|
+
title=None,
|
|
38
|
+
backend="seaborn",
|
|
39
|
+
**kwargs,
|
|
40
|
+
):
|
|
41
|
+
"""
|
|
42
|
+
This is used to create a word cloud.
|
|
43
|
+
|
|
44
|
+
Parameters
|
|
45
|
+
----------
|
|
46
|
+
text : str, optional
|
|
47
|
+
Raw text from which the cloud is generated. Mutually exclusive
|
|
48
|
+
with ``frequencies``.
|
|
49
|
+
frequencies : dict[str, float], optional
|
|
50
|
+
Precomputed word → frequency mapping.
|
|
51
|
+
width, height : int, default=(800, 400)
|
|
52
|
+
Canvas size of the word cloud bitmap in pixels.
|
|
53
|
+
background_color : str, default="white"
|
|
54
|
+
Background colour of the canvas.
|
|
55
|
+
colormap : str, default="viridis"
|
|
56
|
+
Matplotlib colormap used for the words.
|
|
57
|
+
max_words : int, default=200
|
|
58
|
+
Maximum number of words to include in the cloud.
|
|
59
|
+
title : str, optional
|
|
60
|
+
Plot title.
|
|
61
|
+
backend : {"seaborn"}
|
|
62
|
+
Only the Seaborn/Matplotlib backend is supported.
|
|
63
|
+
**kwargs :
|
|
64
|
+
Forwarded to :class:`wordcloud.WordCloud`.
|
|
65
|
+
|
|
66
|
+
Returns
|
|
67
|
+
-------
|
|
68
|
+
None
|
|
69
|
+
"""
|
|
70
|
+
if (text is None) == (frequencies is None):
|
|
71
|
+
raise ValueError("Provide exactly one of `text` or `frequencies`.")
|
|
72
|
+
|
|
73
|
+
self.__text = text
|
|
74
|
+
self.__frequencies = frequencies
|
|
75
|
+
self.__width = width
|
|
76
|
+
self.__height = height
|
|
77
|
+
self.__background_color = background_color
|
|
78
|
+
self.__colormap = colormap
|
|
79
|
+
self.__max_words = max_words
|
|
80
|
+
self.__kwargs = kwargs
|
|
81
|
+
|
|
82
|
+
super().__init__(backend=backend, title=title)
|
|
83
|
+
self._render()
|
|
84
|
+
|
|
85
|
+
def _plot_seaborn(self):
|
|
86
|
+
"""Build a WordCloud bitmap and render it via ``imshow``."""
|
|
87
|
+
wc = WordCloud(
|
|
88
|
+
width=self.__width,
|
|
89
|
+
height=self.__height,
|
|
90
|
+
background_color=self.__background_color,
|
|
91
|
+
colormap=self.__colormap,
|
|
92
|
+
max_words=self.__max_words,
|
|
93
|
+
**self.__kwargs,
|
|
94
|
+
)
|
|
95
|
+
# Two construction paths — pick based on which input the caller gave us.
|
|
96
|
+
if self.__text is not None:
|
|
97
|
+
cloud = wc.generate(self.__text)
|
|
98
|
+
else:
|
|
99
|
+
cloud = wc.generate_from_frequencies(self.__frequencies)
|
|
100
|
+
|
|
101
|
+
plt.imshow(cloud, interpolation="bilinear")
|
|
102
|
+
plt.axis("off")
|
|
103
|
+
if self._title:
|
|
104
|
+
plt.title(self._title)
|
plotify/maps/__init__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""
|
|
2
|
+
plotify.maps
|
|
3
|
+
============
|
|
4
|
+
|
|
5
|
+
Geographic / spatial plots: ChoroplethMap, BubbleMap, HexbinMap,
|
|
6
|
+
Cartogram, ConnectionMap.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from plotify.maps.bubble_map import BubbleMap
|
|
10
|
+
from plotify.maps.cartogram import Cartogram
|
|
11
|
+
from plotify.maps.choropleth_map import ChoroplethMap
|
|
12
|
+
from plotify.maps.connection_map import ConnectionMap
|
|
13
|
+
from plotify.maps.hexbin_map import HexbinMap
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"BubbleMap",
|
|
17
|
+
"Cartogram",
|
|
18
|
+
"ChoroplethMap",
|
|
19
|
+
"ConnectionMap",
|
|
20
|
+
"HexbinMap",
|
|
21
|
+
]
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""
|
|
2
|
+
plotify.maps.bubble_map
|
|
3
|
+
=======================
|
|
4
|
+
|
|
5
|
+
Dual-backend bubble map — markers placed at geographic coordinates, sized
|
|
6
|
+
(and optionally coloured) by a numeric value.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import matplotlib.pyplot as plt
|
|
10
|
+
import plotly.express as px
|
|
11
|
+
|
|
12
|
+
from plotify.base import BasePlot
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class BubbleMap(BasePlot):
|
|
16
|
+
"""
|
|
17
|
+
Bubble map.
|
|
18
|
+
|
|
19
|
+
Seaborn backend draws a scatter on a bare (lat, lon) plane. Plotly
|
|
20
|
+
backend uses :func:`plotly.express.scatter_geo` with real geographic
|
|
21
|
+
projection.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def __init__(
|
|
25
|
+
self,
|
|
26
|
+
df,
|
|
27
|
+
lat,
|
|
28
|
+
lon,
|
|
29
|
+
size,
|
|
30
|
+
color=None,
|
|
31
|
+
hover_name=None,
|
|
32
|
+
scope="world",
|
|
33
|
+
projection="natural earth",
|
|
34
|
+
title=None,
|
|
35
|
+
backend="seaborn",
|
|
36
|
+
**kwargs,
|
|
37
|
+
):
|
|
38
|
+
"""
|
|
39
|
+
This is used to create a bubble map.
|
|
40
|
+
|
|
41
|
+
Parameters
|
|
42
|
+
----------
|
|
43
|
+
df : pandas.DataFrame
|
|
44
|
+
Input data.
|
|
45
|
+
lat, lon : str
|
|
46
|
+
Latitude / longitude column names.
|
|
47
|
+
size : str
|
|
48
|
+
Column used to scale marker size.
|
|
49
|
+
color : str, optional
|
|
50
|
+
Column used to colour-encode markers.
|
|
51
|
+
hover_name : str, optional
|
|
52
|
+
Column used for Plotly hover labels.
|
|
53
|
+
scope : str, default="world"
|
|
54
|
+
Plotly geographic scope.
|
|
55
|
+
projection : str, default="natural earth"
|
|
56
|
+
Plotly projection.
|
|
57
|
+
title : str, optional
|
|
58
|
+
Plot title.
|
|
59
|
+
backend : {"seaborn", "plotly"}, default="seaborn"
|
|
60
|
+
Rendering backend.
|
|
61
|
+
**kwargs :
|
|
62
|
+
Forwarded to the underlying library.
|
|
63
|
+
|
|
64
|
+
Returns
|
|
65
|
+
-------
|
|
66
|
+
None
|
|
67
|
+
"""
|
|
68
|
+
self.__df = df
|
|
69
|
+
self.__lat = lat
|
|
70
|
+
self.__lon = lon
|
|
71
|
+
self.__size = size
|
|
72
|
+
self.__color = color
|
|
73
|
+
self.__hover_name = hover_name
|
|
74
|
+
self.__scope = scope
|
|
75
|
+
self.__projection = projection
|
|
76
|
+
self.__kwargs = kwargs
|
|
77
|
+
|
|
78
|
+
super().__init__(backend=backend, title=title)
|
|
79
|
+
self._render()
|
|
80
|
+
|
|
81
|
+
def _plot_seaborn(self):
|
|
82
|
+
"""Render a plain scatter of (lon, lat) sized by ``size``.
|
|
83
|
+
|
|
84
|
+
This is a non-projected rendering — no coastlines or country
|
|
85
|
+
borders are drawn. For proper geography, prefer the Plotly backend.
|
|
86
|
+
"""
|
|
87
|
+
plt.scatter(
|
|
88
|
+
self.__df[self.__lon],
|
|
89
|
+
self.__df[self.__lat],
|
|
90
|
+
s=self.__df[self.__size],
|
|
91
|
+
c=self.__df[self.__color] if self.__color else None,
|
|
92
|
+
alpha=0.6,
|
|
93
|
+
**self.__kwargs,
|
|
94
|
+
)
|
|
95
|
+
plt.xlabel("lon")
|
|
96
|
+
plt.ylabel("lat")
|
|
97
|
+
if self._title:
|
|
98
|
+
plt.title(self._title)
|
|
99
|
+
|
|
100
|
+
def _plot_plotly(self):
|
|
101
|
+
"""Render using :func:`plotly.express.scatter_geo`."""
|
|
102
|
+
fig = px.scatter_geo(
|
|
103
|
+
self.__df,
|
|
104
|
+
lat=self.__lat,
|
|
105
|
+
lon=self.__lon,
|
|
106
|
+
size=self.__size,
|
|
107
|
+
color=self.__color,
|
|
108
|
+
hover_name=self.__hover_name,
|
|
109
|
+
scope=self.__scope,
|
|
110
|
+
projection=self.__projection,
|
|
111
|
+
title=self._title,
|
|
112
|
+
**self.__kwargs,
|
|
113
|
+
)
|
|
114
|
+
self._fig = fig
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""
|
|
2
|
+
plotify.maps.cartogram
|
|
3
|
+
======================
|
|
4
|
+
|
|
5
|
+
Cartogram — geographic regions distorted in size to encode a numeric
|
|
6
|
+
variable. Building a "true" continuous-area cartogram is non-trivial; this
|
|
7
|
+
class implements the simpler **Dorling cartogram** variant where each
|
|
8
|
+
region is replaced by a circle whose area is proportional to the value,
|
|
9
|
+
positioned at the region centroid.
|
|
10
|
+
|
|
11
|
+
Plotly has no native cartogram primitive, so only the Seaborn/Matplotlib
|
|
12
|
+
backend is implemented.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import matplotlib.pyplot as plt
|
|
16
|
+
import numpy as np
|
|
17
|
+
|
|
18
|
+
from plotify.base import BasePlot
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Cartogram(BasePlot):
|
|
22
|
+
"""
|
|
23
|
+
Dorling-style cartogram.
|
|
24
|
+
|
|
25
|
+
Pass a list of ``(label, lon, lat, value)`` tuples or a dataframe with
|
|
26
|
+
those four columns. Circle areas are scaled so that the largest value
|
|
27
|
+
fits within ``max_radius``.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
# No native Plotly cartogram primitive.
|
|
31
|
+
SUPPORTED_BACKENDS = ("seaborn",)
|
|
32
|
+
|
|
33
|
+
def __init__(
|
|
34
|
+
self,
|
|
35
|
+
df,
|
|
36
|
+
label,
|
|
37
|
+
lon,
|
|
38
|
+
lat,
|
|
39
|
+
value,
|
|
40
|
+
max_radius=10.0,
|
|
41
|
+
cmap="tab20",
|
|
42
|
+
title=None,
|
|
43
|
+
backend="seaborn",
|
|
44
|
+
**kwargs,
|
|
45
|
+
):
|
|
46
|
+
"""
|
|
47
|
+
This is used to create a Dorling cartogram.
|
|
48
|
+
|
|
49
|
+
Parameters
|
|
50
|
+
----------
|
|
51
|
+
df : pandas.DataFrame
|
|
52
|
+
Input data.
|
|
53
|
+
label : str
|
|
54
|
+
Column with region labels.
|
|
55
|
+
lon, lat : str
|
|
56
|
+
Centroid longitude / latitude column names.
|
|
57
|
+
value : str
|
|
58
|
+
Numeric column driving circle size.
|
|
59
|
+
max_radius : float, default=10.0
|
|
60
|
+
Radius (in lon/lat units) of the circle representing the
|
|
61
|
+
maximum value.
|
|
62
|
+
cmap : str, default="tab20"
|
|
63
|
+
Colormap used for per-region colours.
|
|
64
|
+
title : str, optional
|
|
65
|
+
Plot title.
|
|
66
|
+
backend : {"seaborn"}
|
|
67
|
+
Only the Seaborn/Matplotlib backend is supported.
|
|
68
|
+
**kwargs :
|
|
69
|
+
Currently unused.
|
|
70
|
+
|
|
71
|
+
Returns
|
|
72
|
+
-------
|
|
73
|
+
None
|
|
74
|
+
"""
|
|
75
|
+
self.__df = df
|
|
76
|
+
self.__label = label
|
|
77
|
+
self.__lon = lon
|
|
78
|
+
self.__lat = lat
|
|
79
|
+
self.__value = value
|
|
80
|
+
self.__max_radius = max_radius
|
|
81
|
+
self.__cmap = cmap
|
|
82
|
+
self.__kwargs = kwargs
|
|
83
|
+
|
|
84
|
+
super().__init__(backend=backend, title=title)
|
|
85
|
+
self._render()
|
|
86
|
+
|
|
87
|
+
def _plot_seaborn(self):
|
|
88
|
+
"""Draw one matplotlib Circle per region, sized by ``value``."""
|
|
89
|
+
values = self.__df[self.__value].astype(float).values
|
|
90
|
+
max_val = values.max() or 1.0
|
|
91
|
+
# Area-proportional radius — sqrt keeps perceived area linear in value.
|
|
92
|
+
radii = self.__max_radius * np.sqrt(values / max_val)
|
|
93
|
+
|
|
94
|
+
cmap = plt.get_cmap(self.__cmap)
|
|
95
|
+
fig, ax = plt.subplots()
|
|
96
|
+
ax.set_aspect("equal")
|
|
97
|
+
|
|
98
|
+
for i, (_, row) in enumerate(self.__df.iterrows()):
|
|
99
|
+
x = row[self.__lon]
|
|
100
|
+
y = row[self.__lat]
|
|
101
|
+
r = radii[i]
|
|
102
|
+
# Use facecolor explicitly so it does not clash with edgecolor.
|
|
103
|
+
ax.add_patch(
|
|
104
|
+
plt.Circle(
|
|
105
|
+
(x, y),
|
|
106
|
+
r,
|
|
107
|
+
facecolor=cmap(i % 20),
|
|
108
|
+
alpha=0.7,
|
|
109
|
+
edgecolor="black",
|
|
110
|
+
)
|
|
111
|
+
)
|
|
112
|
+
ax.text(x, y, str(row[self.__label]), ha="center", va="center", fontsize=8)
|
|
113
|
+
|
|
114
|
+
# Auto-scale the axis to fit all bubbles.
|
|
115
|
+
ax.set_xlim(
|
|
116
|
+
self.__df[self.__lon].min() - self.__max_radius,
|
|
117
|
+
self.__df[self.__lon].max() + self.__max_radius,
|
|
118
|
+
)
|
|
119
|
+
ax.set_ylim(
|
|
120
|
+
self.__df[self.__lat].min() - self.__max_radius,
|
|
121
|
+
self.__df[self.__lat].max() + self.__max_radius,
|
|
122
|
+
)
|
|
123
|
+
ax.set_xlabel("lon")
|
|
124
|
+
ax.set_ylabel("lat")
|
|
125
|
+
if self._title:
|
|
126
|
+
ax.set_title(self._title)
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""
|
|
2
|
+
plotify.maps.choropleth_map
|
|
3
|
+
===========================
|
|
4
|
+
|
|
5
|
+
Choropleth map — regions coloured by a numeric value.
|
|
6
|
+
|
|
7
|
+
Both backends are implemented. The Seaborn backend uses a GeoDataFrame's
|
|
8
|
+
``plot`` method; the Plotly backend uses :func:`plotly.express.choropleth`
|
|
9
|
+
with either a GeoJSON or a built-in ``locationmode`` such as
|
|
10
|
+
``"country names"``.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import matplotlib.pyplot as plt
|
|
14
|
+
import plotly.express as px
|
|
15
|
+
|
|
16
|
+
from plotify.base import BasePlot
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ChoroplethMap(BasePlot):
|
|
20
|
+
"""
|
|
21
|
+
Region-level choropleth map.
|
|
22
|
+
|
|
23
|
+
Two input modes:
|
|
24
|
+
|
|
25
|
+
* **GeoDataFrame** (both backends) — pass a ``geopandas.GeoDataFrame``
|
|
26
|
+
via ``df`` and the name of the numeric column via ``value``.
|
|
27
|
+
* **Location name** (Plotly only) — pass a regular DataFrame plus
|
|
28
|
+
``locations`` (column name) and ``locationmode="country names"`` (or
|
|
29
|
+
any mode :func:`plotly.express.choropleth` accepts) in ``kwargs``.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def __init__(
|
|
33
|
+
self,
|
|
34
|
+
df,
|
|
35
|
+
value,
|
|
36
|
+
locations=None,
|
|
37
|
+
geojson=None,
|
|
38
|
+
cmap="viridis",
|
|
39
|
+
title=None,
|
|
40
|
+
backend="seaborn",
|
|
41
|
+
**kwargs,
|
|
42
|
+
):
|
|
43
|
+
"""
|
|
44
|
+
This is used to create a choropleth map.
|
|
45
|
+
|
|
46
|
+
Parameters
|
|
47
|
+
----------
|
|
48
|
+
df : pandas.DataFrame or geopandas.GeoDataFrame
|
|
49
|
+
Input data.
|
|
50
|
+
value : str
|
|
51
|
+
Numeric column used for colouring.
|
|
52
|
+
locations : str, optional
|
|
53
|
+
Column with location identifiers (Plotly mode).
|
|
54
|
+
geojson : dict or str, optional
|
|
55
|
+
GeoJSON object or path (Plotly mode).
|
|
56
|
+
cmap : str, default="viridis"
|
|
57
|
+
Colormap name.
|
|
58
|
+
title : str, optional
|
|
59
|
+
Plot title.
|
|
60
|
+
backend : {"seaborn", "plotly"}, default="seaborn"
|
|
61
|
+
Rendering backend.
|
|
62
|
+
**kwargs :
|
|
63
|
+
Forwarded to the underlying library.
|
|
64
|
+
|
|
65
|
+
Returns
|
|
66
|
+
-------
|
|
67
|
+
None
|
|
68
|
+
"""
|
|
69
|
+
self.__df = df
|
|
70
|
+
self.__value = value
|
|
71
|
+
self.__locations = locations
|
|
72
|
+
self.__geojson = geojson
|
|
73
|
+
self.__cmap = cmap
|
|
74
|
+
self.__kwargs = kwargs
|
|
75
|
+
|
|
76
|
+
super().__init__(backend=backend, title=title)
|
|
77
|
+
self._render()
|
|
78
|
+
|
|
79
|
+
def _plot_seaborn(self):
|
|
80
|
+
"""Render via GeoDataFrame.plot (requires a GeoDataFrame)."""
|
|
81
|
+
# Duck-type: any object with a ``plot`` method accepting a ``column``
|
|
82
|
+
# kwarg works (i.e. geopandas.GeoDataFrame).
|
|
83
|
+
if not hasattr(self.__df, "plot"):
|
|
84
|
+
raise TypeError(
|
|
85
|
+
"Seaborn backend requires a GeoDataFrame for ChoroplethMap."
|
|
86
|
+
)
|
|
87
|
+
ax = self.__df.plot(
|
|
88
|
+
column=self.__value,
|
|
89
|
+
cmap=self.__cmap,
|
|
90
|
+
legend=True,
|
|
91
|
+
**self.__kwargs,
|
|
92
|
+
)
|
|
93
|
+
ax.set_axis_off()
|
|
94
|
+
if self._title:
|
|
95
|
+
ax.set_title(self._title)
|
|
96
|
+
|
|
97
|
+
def _plot_plotly(self):
|
|
98
|
+
"""Render using :func:`plotly.express.choropleth`."""
|
|
99
|
+
fig = px.choropleth(
|
|
100
|
+
self.__df,
|
|
101
|
+
locations=self.__locations,
|
|
102
|
+
color=self.__value,
|
|
103
|
+
geojson=self.__geojson,
|
|
104
|
+
color_continuous_scale=self.__cmap,
|
|
105
|
+
title=self._title,
|
|
106
|
+
**self.__kwargs,
|
|
107
|
+
)
|
|
108
|
+
self._fig = fig
|