Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How can I generate more colors on a pie chart in Matplotlib?
When creating pie charts in Matplotlib with many categories, the default color palette may not provide enough distinct colors. You can generate custom colors programmatically to ensure each slice has a unique appearance.
Method 1: Using Random Hex Colors
Generate random hexadecimal colors for each data point ?
import matplotlib.pyplot as plt
import random
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
n = 20
colors = ["#" + ''.join([random.choice('0123456789ABCDEF')
for j in range(6)]) for i in range(n)]
data = np.random.random(n)
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
plt.pie(data, colors=colors)
plt.show()
Method 2: Using Matplotlib Colormap
Generate colors from a predefined colormap for better visual consistency ?
import matplotlib.pyplot as plt
import numpy as np
n = 25
data = np.random.random(n)
colors = plt.cm.Set3(np.linspace(0, 1, n))
fig, ax = plt.subplots(figsize=(8, 6))
ax.pie(data, colors=colors)
ax.set_aspect('equal')
plt.show()
Method 3: Using HSV Color Space
Generate evenly distributed colors using HSV color space for maximum distinction ?
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import hsv_to_rgb
n = 30
data = np.random.random(n)
# Generate colors in HSV space
hues = np.linspace(0, 1, n, endpoint=False)
colors = [hsv_to_rgb([hue, 0.8, 0.9]) for hue in hues]
fig, ax = plt.subplots(figsize=(8, 6))
ax.pie(data, colors=colors)
ax.set_aspect('equal')
plt.show()
Comparison
| Method | Best For | Color Quality |
|---|---|---|
| Random Hex | Quick prototyping | Variable |
| Matplotlib Colormap | Professional visuals | Consistent |
| HSV Color Space | Maximum distinction | Evenly distributed |
Conclusion
For pie charts with many categories, use HSV color space for maximum color distinction or matplotlib colormaps for professional appearance. Random hex colors work well for quick prototyping but may produce similar colors.
Advertisements
