0
# Color Generation and Styling
1
2
Advanced color customization capabilities for word clouds, including random color generation, single-color variations, matplotlib colormap integration, and image-based color extraction for sophisticated visual styling.
3
4
## Capabilities
5
6
### Random Color Generation
7
8
Default color generation function providing random hue variations with consistent saturation and lightness.
9
10
```python { .api }
11
def random_color_func(
12
word=None,
13
font_size=None,
14
position=None,
15
orientation=None,
16
font_path=None,
17
random_state=None
18
):
19
"""
20
Generate random HSL color for word cloud.
21
22
This is the default color function that creates random hues with 80% saturation
23
and 50% lightness for visually appealing color variations.
24
25
Parameters:
26
- word (str, optional): The word being colored (ignored)
27
- font_size (int, optional): Font size of the word (ignored)
28
- position (tuple, optional): Position of the word (ignored)
29
- orientation (int, optional): Orientation of the word (ignored)
30
- font_path (str, optional): Font path (ignored)
31
- random_state (random.Random, optional): Random state for reproducible colors
32
33
Returns:
34
- str: HSL color string in format "hsl(hue, 80%, 50%)"
35
"""
36
```
37
38
### Single Color Variations
39
40
Factory function for creating color functions that generate variations of a single base color.
41
42
```python { .api }
43
def get_single_color_func(color):
44
"""
45
Create color function that generates variations of a single base color.
46
47
Returns a function that generates different brightness values while maintaining
48
the same hue and saturation as the base color.
49
50
Parameters:
51
- color (str): Base color as PIL-compatible color string (e.g., 'deepskyblue', '#00b4d2')
52
53
Returns:
54
- callable: Color function that returns RGB color variations
55
"""
56
```
57
58
### Matplotlib Colormap Integration
59
60
Class for creating color functions based on matplotlib colormaps for professional color schemes.
61
62
```python { .api }
63
class colormap_color_func:
64
def __init__(self, colormap):
65
"""
66
Initialize colormap-based color function.
67
68
Parameters:
69
- colormap (str or matplotlib.colors.Colormap): Colormap name or object
70
"""
71
72
def __call__(self, word, font_size, position, orientation, random_state=None, **kwargs):
73
"""
74
Generate color from matplotlib colormap.
75
76
Parameters:
77
- word (str): The word being colored (ignored)
78
- font_size (int): Font size of the word (ignored)
79
- position (tuple): Position of the word (ignored)
80
- orientation (int): Orientation of the word (ignored)
81
- random_state (random.Random, optional): Random state for color selection
82
- **kwargs: Additional arguments (ignored)
83
84
Returns:
85
- str: RGB color string in format "rgb(r, g, b)"
86
"""
87
```
88
89
### Image-Based Color Generation
90
91
Advanced color generation that extracts colors from reference images for thematically consistent word clouds.
92
93
```python { .api }
94
class ImageColorGenerator:
95
def __init__(self, image, default_color=None):
96
"""
97
Initialize image-based color generator.
98
99
Creates a color function that samples colors from a reference image based on
100
word positions, enabling color schemes that match specific images or themes.
101
102
Parameters:
103
- image (numpy.ndarray): RGB image array with shape (height, width, 3) or (height, width, 4)
104
- default_color (tuple, optional): Fallback RGB color as (r, g, b) for out-of-bounds areas
105
106
Raises:
107
- ValueError: If image dimensions are invalid or canvas is larger than image without default_color
108
"""
109
110
def __call__(self, word, font_size, font_path, position, orientation, **kwargs):
111
"""
112
Generate color based on image region under word.
113
114
Samples the average color from the image region that will be covered by the word,
115
creating visually cohesive word clouds that match the reference image's color palette.
116
117
Parameters:
118
- word (str): The word being colored
119
- font_size (int): Font size in pixels
120
- font_path (str): Path to font file
121
- position (tuple): Word position as (x, y)
122
- orientation (int): Word orientation in degrees
123
- **kwargs: Additional arguments (ignored)
124
125
Returns:
126
- str: RGB color string in format "rgb(r, g, b)"
127
128
Raises:
129
- ValueError: If word extends beyond image bounds and no default_color provided
130
- NotImplementedError: For grayscale images (not yet supported)
131
"""
132
```
133
134
## Usage Examples
135
136
### Random Colors
137
138
```python
139
from wordcloud import WordCloud, random_color_func
140
141
# Use default random colors
142
wc = WordCloud(color_func=random_color_func)
143
wc.generate(text)
144
```
145
146
### Single Color Variations
147
148
```python
149
from wordcloud import WordCloud, get_single_color_func
150
151
# Create variations of blue
152
blue_func = get_single_color_func('deepskyblue')
153
wc = WordCloud(color_func=blue_func)
154
wc.generate(text)
155
156
# Using hex color
157
red_func = get_single_color_func('#FF4500')
158
wc = WordCloud(color_func=red_func)
159
wc.generate(text)
160
```
161
162
### Matplotlib Colormaps
163
164
```python
165
from wordcloud import WordCloud
166
167
# Use built-in colormap support
168
wc = WordCloud(colormap='plasma')
169
wc.generate(text)
170
171
# Or create custom colormap function
172
from wordcloud import colormap_color_func
173
color_func = colormap_color_func('viridis')
174
wc = WordCloud(color_func=color_func)
175
wc.generate(text)
176
```
177
178
### Image-Based Colors
179
180
```python
181
from wordcloud import WordCloud, ImageColorGenerator
182
import numpy as np
183
from PIL import Image
184
185
# Load reference image
186
image = np.array(Image.open('reference.jpg'))
187
188
# Create color generator
189
color_generator = ImageColorGenerator(image)
190
191
# Generate word cloud with image colors
192
wc = WordCloud(color_func=color_generator, mask=image)
193
wc.generate(text)
194
wc.to_file('colored_wordcloud.png')
195
```
196
197
### Custom Color Functions
198
199
```python
200
from wordcloud import WordCloud
201
202
# Define custom color function
203
def custom_color_func(word, font_size, position, orientation, **kwargs):
204
# Color words based on length
205
if len(word) > 6:
206
return 'rgb(255, 100, 100)' # Red for long words
207
elif len(word) > 3:
208
return 'rgb(100, 255, 100)' # Green for medium words
209
else:
210
return 'rgb(100, 100, 255)' # Blue for short words
211
212
wc = WordCloud(color_func=custom_color_func)
213
wc.generate(text)
214
```
215
216
### Recoloring Existing Word Clouds
217
218
```python
219
from wordcloud import WordCloud, get_single_color_func
220
221
# Generate word cloud
222
wc = WordCloud().generate(text)
223
224
# Recolor with different scheme
225
purple_func = get_single_color_func('purple')
226
wc.recolor(color_func=purple_func)
227
228
# Or use colormap
229
wc.recolor(colormap='cool')
230
```