forked from reina-peh/Anaconda-Data-Science-Expo-2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHistogram with KDE.py
54 lines (40 loc) · 1.88 KB
/
Histogram with KDE.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import norm
data = pd.read_csv("C:/Users/reina/Documents/Downloads/hapiness_report_2022_cleaned.csv")
color_map = plt.cm.plasma
mu, std = norm.fit(data['score'])
plt.figure(figsize=(12,7))
n, bins, patches = plt.hist(data['score'], bins=20, rwidth=0.8, density=False, alpha=0.75, edgecolor='white')
# Color code each bin based on its position
col = (bins[:-1] - min(bins[:-1])) / (max(bins[:-1]) - min(bins[:-1]))
for c, p in zip(col, patches):
plt.setp(p, 'facecolor', color_map(c))
# axes
ax = plt.gca()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_color('#666666')
ax.spines['left'].set_color('#666666')
# y-axis labels
max_ylim = max([patch.get_height() for patch in patches])
ax.set_yticks(range(0, int(max_ylim) + 1, 2))
xmin, xmax = plt.xlim()
x = np.linspace(xmin, xmax, 100)
p = norm.pdf(x, mu, std) * len(data['score']) * (bins[1] - bins[0])
plt.plot(x, p, '#006400', linewidth=2, linestyle=':')
# Annotate with mean with dashed/dotted line
plt.axvline(mu, color='red', linestyle='dashed', linewidth=1)
plt.text(mu*0.87, max_ylim*0.95, 'Mean: {:.2f}'.format(mu), color='red', fontsize=14)
for i in range(len(patches)):
height = patches[i].get_height()
if height > 0:
plt.text(patches[i].get_x() + patches[i].get_width() / 2., height + 0.5,
f"{int(height)}", ha="center", va="bottom", fontsize=12, color='black')
plt.title('Distribution of Happiness Scores (2022)', fontsize=18, fontweight='bold', color='#333333', y=1.2)
plt.xlabel('Happiness Score', fontsize=14, color='#333333')
plt.ylabel('Number of Countries', fontsize=14, color='#333333')
plt.tight_layout()
plt.grid(axis='y', linestyle='-.', linewidth=0.5, alpha=0.5)
plt.savefig("C:/Users/reina/Documents/Downloads/distribution_bar_chart.svg", transparent=True, format="svg")
plt.show()