KDE Plot

Product Rating Distribution

KDE showing customer product ratings with sentiment zones.

Output
Product Rating Distribution
Python
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats

np.random.seed(55)

# Ratings tend to be J-shaped (more high ratings)
ratings = np.concatenate([
    np.random.normal(4.3, 0.5, 600),
    np.random.normal(2.5, 0.8, 150),
    np.random.uniform(1, 5, 250)
])
ratings = np.clip(ratings, 1, 5)

kde = stats.gaussian_kde(ratings)
x = np.linspace(1, 5, 500)
y = kde(x)

fig, ax = plt.subplots(figsize=(12, 6), facecolor='#0a0a0f')
ax.set_facecolor('#0a0a0f')

# Sentiment-based coloring
for i in range(len(x)-1):
    if x[i] < 2:
        color = '#F5276C'  # Negative
    elif x[i] < 3:
        color = '#F54927'  # Mixed negative
    elif x[i] < 4:
        color = '#F5B027'  # Neutral
    else:
        color = '#6CF527'  # Positive
    ax.fill_between(x[i:i+2], y[i:i+2], alpha=0.6, color=color)

ax.plot(x, y, color='#F5B027', linewidth=3)
ax.plot(x, y, color='#F5B027', linewidth=8, alpha=0.2)

# Mean line
mean_rating = np.mean(ratings)
ax.axvline(mean_rating, color='white', linestyle='--', linewidth=2)
ax.text(mean_rating+0.1, max(y)*0.85, f'Avg: {mean_rating:.2f}', color='white', fontsize=11, fontweight='bold')

ax.set_xlabel('Rating (1-5 stars)', fontsize=12, color='white', fontweight='500')
ax.set_ylabel('Density', fontsize=12, color='white', fontweight='500')
ax.set_title('Product Rating Distribution', fontsize=16, color='white', fontweight='bold', pad=15)

ax.tick_params(colors='white', labelsize=10)
for spine in ax.spines.values():
    spine.set_color('#334155')
ax.grid(True, alpha=0.1, color='white')
ax.set_xlim(1, 5)

plt.tight_layout()
plt.show()
Library

Matplotlib

Category

Statistical

Did this help you?

Support PyLucid to keep it free & growing

Support