From a423c78282a9d1162f2dc77eea8ecafe83f17e5a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bertrand=20N=C3=A9ron?= <bneron@pasteur.fr>
Date: Wed, 2 Oct 2024 11:45:48 +0200
Subject: [PATCH] improve ipywidget exo/demo

---
 .../seaborn_TP_solutions_happiness2016.ipynb  | 43 ++++++++++++++++++-
 1 file changed, 42 insertions(+), 1 deletion(-)

diff --git a/notebooks/seaborn_TP_solutions_happiness2016.ipynb b/notebooks/seaborn_TP_solutions_happiness2016.ipynb
index 7b7e292..55d372b 100644
--- a/notebooks/seaborn_TP_solutions_happiness2016.ipynb
+++ b/notebooks/seaborn_TP_solutions_happiness2016.ipynb
@@ -584,15 +584,56 @@
    "metadata": {},
    "outputs": [],
    "source": [
+    "\n",
     "@interact(region=widgets.Dropdown(options=regions))\n",
     "def plot_counts(region):\n",
     "    data = ha_df.loc[ha_df['Region'] == region]\n",
     "    ax = sns.barplot(data=data, y='Happiness Score', x='Country')\n",
-    "    \n",
     "    ax.set_xticks(data.Country)\n",
     "    ax.set_xticklabels(data.Country, rotation=45, ha='right', rotation_mode='anchor')\n",
     "    "
    ]
+  },
+  {
+   "cell_type": "markdown",
+   "id": "3f4bd68e-eb26-46f8-a00f-86f9d0570580",
+   "metadata": {},
+   "source": [
+    "You can customize your figure as classical seaborn/matplotib figure\n",
+    "\n",
+    "for instance to display the value above each bar"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "id": "7bcee7c5-f1c2-4035-9b7c-e68e1d73a932",
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "\n",
+    "@interact(region=widgets.Dropdown(options=regions))\n",
+    "def plot_counts(region):\n",
+    "    data = ha_df.loc[ha_df['Region'] == region]\n",
+    "    ax = sns.barplot(data=data, y='Happiness Score', x='Country')\n",
+    "    for i in ax.containers:\n",
+    "        # add label on each bar https://www.geeksforgeeks.org/how-to-show-values-on-seaborn-barplot/\n",
+    "        ax.bar_label(i, fmt=\"{:.2f}\", rotation='vertical', padding=3)\n",
+    "        \n",
+    "    ax.set_xticks(data.Country)\n",
+    "    ax.set_xticklabels(data.Country, rotation=45, ha='right', rotation_mode='anchor')\n",
+    "    ax.margins(y=0.1) # add margin to avoid to have label outside the barplotboundaries, here add 10% white space vertically \n",
+    "    # https://stackoverflow.com/questions/72662991/how-can-i-prevent-bar-labels-from-going-outside-the-barplot-boundaries-range\n",
+    "    "
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "id": "d78b7b86-ecaa-4d27-80ca-2d3e46c2aca3",
+   "metadata": {},
+   "outputs": [],
+   "source": []
   }
  ],
  "metadata": {
-- 
GitLab