Skip to content

Commit d918932

Browse files
lionelkuschdierickxsimon
authored andcommitted
Add a text for displaying values on histogram. (skrub-data#1496)
1 parent 3016ff4 commit d918932

1 file changed

Lines changed: 22 additions & 8 deletions

File tree

skrub/_reporting/_plotting.py

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -307,25 +307,39 @@ def value_counts(value_counts, n_unique, n_rows, color=COLOR_0):
307307
fig, ax = plt.subplots()
308308
_despine(ax)
309309
rects = ax.barh(list(map(str, range(len(values)))), counts, color=color)
310-
percent = [_utils.format_percent(c / n_rows) for c in counts]
311-
large_percent = [
312-
f"{p: >6}" if c > counts[-1] / 2 else "" for (p, c) in zip(percent, counts)
310+
string_value = [_utils.format_number(c) for c in counts]
311+
large_string = [
312+
f"{s: >6}" if c > counts[-1] / 2 else "" for (s, c) in zip(string_value, counts)
313313
]
314-
small_percent = [
315-
p if c <= counts[-1] / 2 else "" for (p, c) in zip(percent, counts)
314+
small_string = [
315+
s if c <= counts[-1] / 2 else "" for (s, c) in zip(string_value, counts)
316316
]
317317

318318
# those are written on top of the orange bars so we write them in black
319-
ax.bar_label(rects, large_percent, padding=-30, color="black", fontsize=8)
319+
ax.bar_label(rects, large_string, padding=-30, color="black", fontsize=8)
320320
# those are written on top of the background so we write them in foreground color
321321
ax.bar_label(
322-
rects, small_percent, padding=5, color=_TEXT_COLOR_PLACEHOLDER, fontsize=8
322+
rects, small_string, padding=5, color=_TEXT_COLOR_PLACEHOLDER, fontsize=8
323+
)
324+
325+
percent = [_utils.format_percent(c / n_rows) for c in counts]
326+
# add the percentage of each bar on the top of the figure
327+
ax_percentage = ax.twinx()
328+
ax_percentage.set_ylim(ax.get_ylim())
329+
ax_percentage.set_yticks(ticks=range(len(counts)))
330+
ax_percentage.tick_params(axis="both", length=0)
331+
ax_percentage.set_yticklabels(
332+
labels=percent,
333+
color=_TEXT_COLOR_PLACEHOLDER,
334+
fontsize=8,
323335
)
324336

325337
ax.set_yticks(ax.get_yticks())
326338
ax.set_yticklabels(list(map(str, values)))
339+
ax.spines[["right", "top"]].set_visible(False)
340+
ax_percentage.spines[["right", "top"]].set_visible(False)
327341
if title is not None:
328342
ax.set_title(title)
329343

330-
_adjust_fig_size(fig, ax, 1.0, 0.2 * len(values))
344+
_adjust_fig_size(fig, ax, 1.3, 0.2 * len(values))
331345
return _serialize(fig)

0 commit comments

Comments
 (0)