heatmap_cli 0.27.1__tar.gz → 0.28.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. {heatmap_cli-0.27.1/src/heatmap_cli.egg-info → heatmap_cli-0.28.0}/PKG-INFO +5 -2
  2. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/README.md +4 -1
  3. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/pyproject.toml +1 -1
  4. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/src/heatmap_cli/cli.py +21 -0
  5. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/src/heatmap_cli/heatmap.py +212 -9
  6. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0/src/heatmap_cli.egg-info}/PKG-INFO +5 -2
  7. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/src/heatmap_cli.egg-info/SOURCES.txt +1 -0
  8. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_annotation_truncation.py +1 -0
  9. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_heatmap_direct.py +1 -0
  10. heatmap_cli-0.28.0/tests/test_heatmap_style_option.py +179 -0
  11. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_no_annotate.py +2 -0
  12. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/LICENSE.md +0 -0
  13. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/setup.cfg +0 -0
  14. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/src/heatmap_cli/__init__.py +0 -0
  15. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/src/heatmap_cli/__main__.py +0 -0
  16. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/src/heatmap_cli/py.typed +0 -0
  17. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/src/heatmap_cli.egg-info/dependency_links.txt +0 -0
  18. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/src/heatmap_cli.egg-info/entry_points.txt +0 -0
  19. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/src/heatmap_cli.egg-info/requires.txt +0 -0
  20. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/src/heatmap_cli.egg-info/top_level.txt +0 -0
  21. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_agg_backend.py +0 -0
  22. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_animate_by_week.py +0 -0
  23. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_animate_future_day.py +0 -0
  24. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_animate_no_frames.py +0 -0
  25. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_animate_open.py +0 -0
  26. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_annotate_flag.py +0 -0
  27. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_cbar_flag.py +0 -0
  28. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_cmap_option.py +0 -0
  29. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_cmax_option.py +0 -0
  30. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_cmin_option.py +0 -0
  31. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_configure_cbar.py +0 -0
  32. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_debug_flag.py +0 -0
  33. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_demo_option.py +0 -0
  34. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_end_date_option.py +0 -0
  35. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_env_flag.py +0 -0
  36. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_heatmap_errors.py +0 -0
  37. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_heatmap_open.py +0 -0
  38. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_heatmap_utils.py +0 -0
  39. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_heatmap_wrapper.py +0 -0
  40. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_help_flag.py +0 -0
  41. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_iso_53_week_year.py +0 -0
  42. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_open_heatmap.py +0 -0
  43. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_output_dir_option.py +0 -0
  44. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_purge_flag.py +0 -0
  45. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_quiet_flag.py +0 -0
  46. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_refresh_output_dir.py +0 -0
  47. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_setup_logging.py +0 -0
  48. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_start_date_option.py +0 -0
  49. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_supported_formats.py +0 -0
  50. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_title_option.py +0 -0
  51. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_version_flag.py +0 -0
  52. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_week_option.py +0 -0
  53. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_year_option.py +0 -0
  54. {heatmap_cli-0.27.1 → heatmap_cli-0.28.0}/tests/test_yes_flag.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: heatmap_cli
3
- Version: 0.27.1
3
+ Version: 0.28.0
4
4
  Summary: A console program that generates a yearly calendar heatmap.
5
5
  Author-email: Kian-Meng Ang <kianmeng@cpan.org>
6
6
  License-Expression: AGPL-3.0-or-later
@@ -59,7 +59,8 @@ usage: heatmap_cli [--demo [NUMBER_OF_COLORMAP]] [--seed SEED] [-y YEAR]
59
59
  [-o] [-p] [-t TITLE] [-u AUTHOR] [-f IMAGE_FORMAT]
60
60
  [-c COLORMAP] [-i COLORMAP_MIN_VALUE]
61
61
  [-x COLORMAP_MAX_VALUE] [-b]
62
- [-a | --annotate | --no-annotate] [--animate-by-week] [-q]
62
+ [-a | --annotate | --no-annotate]
63
+ [--heatmap-style HEATMAP_STYLE] [--animate-by-week] [-q]
63
64
  [-Y] [-d] [-E] [-V] [-h]
64
65
  [CSV_FILENAME]
65
66
 
@@ -142,6 +143,8 @@ options:
142
143
  show colorbar (default: False)
143
144
  -a, --annotate, --no-annotate
144
145
  add count to each heatmap region (use --no-annotate to disable)
146
+ --heatmap-style HEATMAP_STYLE
147
+ set the annotation style for each heatmap region, either 'number' for counts or 'grade' for letter grades (default: 'number')
145
148
  --animate-by-week
146
149
  create an animation for each day of the current week
147
150
  -q, --quiet
@@ -30,7 +30,8 @@ usage: heatmap_cli [--demo [NUMBER_OF_COLORMAP]] [--seed SEED] [-y YEAR]
30
30
  [-o] [-p] [-t TITLE] [-u AUTHOR] [-f IMAGE_FORMAT]
31
31
  [-c COLORMAP] [-i COLORMAP_MIN_VALUE]
32
32
  [-x COLORMAP_MAX_VALUE] [-b]
33
- [-a | --annotate | --no-annotate] [--animate-by-week] [-q]
33
+ [-a | --annotate | --no-annotate]
34
+ [--heatmap-style HEATMAP_STYLE] [--animate-by-week] [-q]
34
35
  [-Y] [-d] [-E] [-V] [-h]
35
36
  [CSV_FILENAME]
36
37
 
@@ -113,6 +114,8 @@ options:
113
114
  show colorbar (default: False)
114
115
  -a, --annotate, --no-annotate
115
116
  add count to each heatmap region (use --no-annotate to disable)
117
+ --heatmap-style HEATMAP_STYLE
118
+ set the annotation style for each heatmap region, either 'number' for counts or 'grade' for letter grades (default: 'number')
116
119
  --animate-by-week
117
120
  create an animation for each day of the current week
118
121
  -q, --quiet
@@ -28,7 +28,7 @@ classifiers = [
28
28
  "Programming Language :: Python",
29
29
  "Topic :: Scientific/Engineering :: Visualization",
30
30
  ]
31
- version = "0.27.1"
31
+ version = "0.28.0"
32
32
  keywords = ["heatmap", "cli", "visualization", "calendar", "data-viz"]
33
33
  dependencies = [
34
34
  "matplotlib",
@@ -351,6 +351,19 @@ def build_parser() -> argparse.ArgumentParser:
351
351
  help="add count to each heatmap region (use --no-annotate to disable)",
352
352
  )
353
353
 
354
+ parser.add_argument(
355
+ "--heatmap-style",
356
+ dest="heatmap_style",
357
+ choices=("number", "grade"),
358
+ default="number",
359
+ help=(
360
+ "set the annotation style for each heatmap region, either "
361
+ "'number' for counts or 'grade' for letter grades "
362
+ "(default: '%(default)s')"
363
+ ),
364
+ metavar="HEATMAP_STYLE",
365
+ )
366
+
354
367
  parser.add_argument(
355
368
  "--animate-by-week",
356
369
  default=False,
@@ -663,6 +676,14 @@ def _process_args(
663
676
  if parsed_args.format == "gif":
664
677
  parsed_args.animate_by_week = True
665
678
 
679
+ # The grade style draws the colored grade legend, which already maps
680
+ # grades to colors, so a colorbar would only duplicate it.
681
+ if parsed_args.cbar and parsed_args.heatmap_style == "grade":
682
+ logger.warning(
683
+ "argument --cbar: ignored with --heatmap-style grade, "
684
+ "the legend shows the colors instead.",
685
+ )
686
+
666
687
  return parsed_args
667
688
 
668
689
 
@@ -32,13 +32,17 @@ from typing import TYPE_CHECKING, Any, cast
32
32
  if TYPE_CHECKING:
33
33
  import argparse
34
34
 
35
+ from matplotlib.artist import Artist
35
36
  from matplotlib.axes import Axes
37
+ from matplotlib.collections import QuadMesh
38
+ from matplotlib.colors import Colormap, Normalize
36
39
 
37
40
  import matplotlib as mpl
38
41
  import pandas as pd
39
42
  import seaborn as sns
40
43
  from matplotlib.backends.backend_agg import FigureCanvasAgg
41
44
  from matplotlib.figure import Figure
45
+ from matplotlib.offsetbox import AnnotationBbox, HPacker, TextArea, VPacker
42
46
  from PIL import Image
43
47
 
44
48
  # Define constants for figure and image settings
@@ -53,6 +57,7 @@ GIF_LOOP_COUNT = 0
53
57
  DEFAULT_TICK_LABEL_FONTSIZE = 9
54
58
  ANNOTATION_FONTSIZE = 8
55
59
  TITLE_FONTSIZE = 11
60
+ GRADE_LEGEND_FONTSIZE = 9
56
61
 
57
62
  # Define constants for colorbar settings
58
63
  COLORBAR_PAD = 0.10
@@ -66,6 +71,47 @@ WEEKS_IN_YEAR = 52
66
71
  # Define constants for annotation thresholds
67
72
  ANNOTATION_THRESHOLD = 100
68
73
 
74
+ # Letter grade scale for --heatmap-style grade: X (10k+), A (7.5k-10k),
75
+ # B (5k-7.5k), C (2.5k-5k), D (1k-2.5k), E (<1k), and a dot for a day
76
+ # without steps. Counts are in the truncated annotation units (hundreds
77
+ # of steps), so 100 is 10,000 steps.
78
+ GRADE_THRESHOLDS = (
79
+ (100, "X"),
80
+ (75, "A"),
81
+ (50, "B"),
82
+ (25, "C"),
83
+ (10, "D"),
84
+ )
85
+ GRADE_FALLBACK = "E"
86
+ GRADE_ZERO = "."
87
+
88
+ # Grade scale legend shown below a heatmap with graded annotations. Each
89
+ # entry is the grade letter, its step range label, and a representative
90
+ # count in the truncated annotation units, used to sample the heatmap
91
+ # color that the letter is drawn in.
92
+ GRADE_LEGEND_LABEL = "Legend:"
93
+ GRADE_LEGEND_ENTRIES = (
94
+ ("X", "10k+", 110),
95
+ ("A", "7.5-10k", 87),
96
+ ("B", "5-7.5k", 62),
97
+ ("C", "2.5-5k", 37),
98
+ ("D", "1-2.5k", 17),
99
+ ("E", "<1k", 5),
100
+ (GRADE_ZERO, "0", 0),
101
+ )
102
+
103
+ # Vertical distance in points between the axes bottom and the top of the
104
+ # grade legend block.
105
+ GRADE_LEGEND_OFFSET = -18
106
+
107
+ # Vertical spacing in points between the week label and the grade legend
108
+ # below it.
109
+ WEEK_LEGEND_GAP = 4
110
+
111
+ # Vertical spacing in points between the grade legend row and the
112
+ # "Generated by" row below it.
113
+ LEGEND_GENERATED_GAP = 2
114
+
69
115
  # Define constants for default title strings
70
116
  DEFAULT_TITLE_PREFIX = "Year {config.year}: Total Daily Walking Steps"
71
117
  DEFAULT_TITLE_WEEK_SUFFIX = " Through Week {config.week:02d}"
@@ -561,11 +607,14 @@ def _setup_plot_artists(
561
607
  res = sns.heatmap(dataframe, **options)
562
608
 
563
609
  if config.annotate:
564
- _apply_annotations(res)
610
+ _apply_annotations(res, config.heatmap_style)
565
611
 
566
- if config.cbar:
612
+ if _colorbar_enabled(config):
567
613
  _configure_cbar(res)
568
614
 
615
+ if config.annotate and config.heatmap_style == "grade":
616
+ _add_grade_legend(axis, res, _generated_by_label(cmap, config))
617
+
569
618
  return fig, axis
570
619
 
571
620
 
@@ -606,6 +655,41 @@ def _generate_heatmap(
606
655
  return img_filename
607
656
 
608
657
 
658
+ def _colorbar_enabled(config: argparse.Namespace) -> bool:
659
+ """Return whether the heatmap draws a colorbar.
660
+
661
+ The grade style draws the colored grade legend instead, which already
662
+ maps grades to colors, so --cbar is ignored with it.
663
+
664
+ Args:
665
+ config (argparse.Namespace): Config from command line arguments.
666
+
667
+ Returns:
668
+ bool: True when the colorbar should be drawn.
669
+ """
670
+ return bool(config.cbar and config.heatmap_style != "grade")
671
+
672
+
673
+ def _generated_by_label(cmap: str, config: argparse.Namespace) -> str:
674
+ """Build the "Generated by" label.
675
+
676
+ Shown under the colorbar, or as the last grade legend row when the
677
+ grade style has no colorbar.
678
+
679
+ Args:
680
+ cmap (str): Colormap name used for the heatmap.
681
+ config (argparse.Namespace): Config from command line arguments.
682
+
683
+ Returns:
684
+ str: The "Generated by" label, noting the truncated counts when
685
+ numeric annotations are shown.
686
+ """
687
+ label = COLORBAR_BASE_LABEL.format(cmap=cmap)
688
+ if config.annotate and config.heatmap_style != "grade":
689
+ label += COLORBAR_ANNOTATION_SUFFIX
690
+ return label
691
+
692
+
609
693
  def _configure_heatmap_options(
610
694
  config: argparse.Namespace,
611
695
  cmap: str,
@@ -623,7 +707,7 @@ def _configure_heatmap_options(
623
707
  """
624
708
  cbar_options = {
625
709
  "orientation": "horizontal",
626
- "label": COLORBAR_BASE_LABEL.format(cmap=cmap),
710
+ "label": _generated_by_label(cmap, config),
627
711
  "pad": COLORBAR_PAD,
628
712
  "aspect": COLORBAR_ASPECT,
629
713
  "extend": "max",
@@ -633,7 +717,7 @@ def _configure_heatmap_options(
633
717
  "fmt": "",
634
718
  "square": True,
635
719
  "cmap": cmap,
636
- "cbar": config.cbar,
720
+ "cbar": _colorbar_enabled(config),
637
721
  "cbar_kws": cbar_options,
638
722
  }
639
723
 
@@ -643,9 +727,6 @@ def _configure_heatmap_options(
643
727
  options["vmax"] = config.cmap_max
644
728
 
645
729
  if config.annotate:
646
- cbar_options["label"] = (
647
- f"{cbar_options['label']}{COLORBAR_ANNOTATION_SUFFIX}"
648
- )
649
730
  options.update(
650
731
  {
651
732
  "annot": True,
@@ -656,20 +737,142 @@ def _configure_heatmap_options(
656
737
  return options
657
738
 
658
739
 
659
- def _apply_annotations(res: Axes) -> None:
740
+ def _apply_annotations(res: Axes, style: str) -> None:
660
741
  """Apply custom annotations to the heatmap cells.
661
742
 
662
743
  Args:
663
744
  res (Axes): The matplotlib axes object returned by seaborn.
745
+ style (str): The annotation style, "number" for truncated counts or
746
+ "grade" for letter grades.
664
747
  """
665
748
  for text in res.texts:
666
749
  count = int(float(text.get_text()))
667
- if count >= ANNOTATION_THRESHOLD:
750
+ if style == "grade":
751
+ text.set_text(_grade_for_count(count))
752
+ elif count >= ANNOTATION_THRESHOLD:
668
753
  text.set_text(">" + str(count)[0])
669
754
  else:
670
755
  text.set_text(str(count))
671
756
 
672
757
 
758
+ def _grade_legend_row(colormap: Colormap, norm: Normalize) -> HPacker:
759
+ """Build the grade legend row with heatmap colored grade letters.
760
+
761
+ Args:
762
+ colormap (Colormap): Colormap of the heatmap.
763
+ norm (Normalize): Norm mapping truncated counts to heatmap colors.
764
+
765
+ Returns:
766
+ HPacker: The packed legend row.
767
+ """
768
+ children: list[Artist] = [
769
+ TextArea(
770
+ GRADE_LEGEND_LABEL,
771
+ textprops={"fontsize": GRADE_LEGEND_FONTSIZE},
772
+ ),
773
+ ]
774
+ for index, (grade, label, value) in enumerate(GRADE_LEGEND_ENTRIES):
775
+ gap = " " if index == 0 else " "
776
+ children.append(
777
+ TextArea(
778
+ f"{gap}{grade}",
779
+ textprops={
780
+ "fontsize": GRADE_LEGEND_FONTSIZE,
781
+ "fontweight": "bold",
782
+ "color": colormap(norm(value)),
783
+ },
784
+ ),
785
+ )
786
+ children.append(
787
+ TextArea(
788
+ f" {label}",
789
+ textprops={"fontsize": GRADE_LEGEND_FONTSIZE},
790
+ ),
791
+ )
792
+ return HPacker(children=children, align="center", pad=0, sep=0)
793
+
794
+
795
+ def _add_grade_legend(axis: Axes, res: Axes, generated_by: str) -> None:
796
+ """Place the colored grade legend below the heatmap.
797
+
798
+ The legend replaces the week x-axis label and the colorbar, because the
799
+ legend already maps grades to colors. The "Generated by" line that would
800
+ sit under the colorbar is kept as the last row of the legend. The legend
801
+ cannot be a regular axis label because every grade letter is drawn in
802
+ its own heatmap color, which plain text objects do not support.
803
+
804
+ Args:
805
+ axis (Axes): Matplotlib axes object with the heatmap.
806
+ res (Axes): The axes object returned by seaborn, used to sample
807
+ the legend colors from the heatmap.
808
+ generated_by (str): The "Generated by" line shown as the last row.
809
+ """
810
+ mesh = cast("QuadMesh", res.collections[0])
811
+ legend_row = _grade_legend_row(mesh.cmap, mesh.norm)
812
+
813
+ legend_block = VPacker(
814
+ children=[
815
+ legend_row,
816
+ TextArea(
817
+ generated_by,
818
+ textprops={"fontsize": GRADE_LEGEND_FONTSIZE},
819
+ ),
820
+ ],
821
+ align="left",
822
+ pad=0,
823
+ sep=LEGEND_GENERATED_GAP,
824
+ )
825
+
826
+ children: list[Artist] = []
827
+ xlabel = axis.get_xlabel()
828
+ axis.set_xlabel("")
829
+ if xlabel:
830
+ children.append(
831
+ TextArea(
832
+ xlabel,
833
+ textprops={"fontsize": GRADE_LEGEND_FONTSIZE},
834
+ ),
835
+ )
836
+ children.append(legend_block)
837
+
838
+ axis.add_artist(
839
+ AnnotationBbox(
840
+ VPacker(
841
+ children=children,
842
+ align="left",
843
+ pad=0,
844
+ sep=WEEK_LEGEND_GAP,
845
+ ),
846
+ xy=(0, 0),
847
+ xycoords=axis.transAxes,
848
+ xybox=(0, GRADE_LEGEND_OFFSET),
849
+ boxcoords="offset points",
850
+ box_alignment=(0, 1),
851
+ frameon=False,
852
+ pad=0,
853
+ ),
854
+ )
855
+
856
+
857
+ def _grade_for_count(count: int) -> str:
858
+ """Map a truncated daily count to a letter grade.
859
+
860
+ Args:
861
+ count (int): The truncated count in hundreds of steps, as shown by
862
+ the numeric annotations.
863
+
864
+ Returns:
865
+ str: The letter grade for the count, or a dot when there were no
866
+ steps.
867
+ """
868
+ if count == 0:
869
+ return GRADE_ZERO
870
+ for threshold, grade in GRADE_THRESHOLDS:
871
+ if count >= threshold:
872
+ return grade
873
+ return GRADE_FALLBACK
874
+
875
+
673
876
  def _configure_cbar(res: Axes) -> None:
674
877
  """Configure the colorbar of the heatmap.
675
878
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: heatmap_cli
3
- Version: 0.27.1
3
+ Version: 0.28.0
4
4
  Summary: A console program that generates a yearly calendar heatmap.
5
5
  Author-email: Kian-Meng Ang <kianmeng@cpan.org>
6
6
  License-Expression: AGPL-3.0-or-later
@@ -59,7 +59,8 @@ usage: heatmap_cli [--demo [NUMBER_OF_COLORMAP]] [--seed SEED] [-y YEAR]
59
59
  [-o] [-p] [-t TITLE] [-u AUTHOR] [-f IMAGE_FORMAT]
60
60
  [-c COLORMAP] [-i COLORMAP_MIN_VALUE]
61
61
  [-x COLORMAP_MAX_VALUE] [-b]
62
- [-a | --annotate | --no-annotate] [--animate-by-week] [-q]
62
+ [-a | --annotate | --no-annotate]
63
+ [--heatmap-style HEATMAP_STYLE] [--animate-by-week] [-q]
63
64
  [-Y] [-d] [-E] [-V] [-h]
64
65
  [CSV_FILENAME]
65
66
 
@@ -142,6 +143,8 @@ options:
142
143
  show colorbar (default: False)
143
144
  -a, --annotate, --no-annotate
144
145
  add count to each heatmap region (use --no-annotate to disable)
146
+ --heatmap-style HEATMAP_STYLE
147
+ set the annotation style for each heatmap region, either 'number' for counts or 'grade' for letter grades (default: 'number')
145
148
  --animate-by-week
146
149
  create an animation for each day of the current week
147
150
  -q, --quiet
@@ -31,6 +31,7 @@ tests/test_env_flag.py
31
31
  tests/test_heatmap_direct.py
32
32
  tests/test_heatmap_errors.py
33
33
  tests/test_heatmap_open.py
34
+ tests/test_heatmap_style_option.py
34
35
  tests/test_heatmap_utils.py
35
36
  tests/test_heatmap_wrapper.py
36
37
  tests/test_help_flag.py
@@ -32,6 +32,7 @@ def test_annotation_truncation(tmpdir):
32
32
  output_dir=str(tmpdir),
33
33
  format="png",
34
34
  open=False,
35
+ heatmap_style="number",
35
36
  )
36
37
 
37
38
  df = pd.DataFrame(
@@ -37,6 +37,7 @@ def test_generate_heatmap_direct(tmpdir):
37
37
  output_dir=str(tmpdir),
38
38
  format="png",
39
39
  open=False,
40
+ heatmap_style="number",
40
41
  )
41
42
 
42
43
  # Create a small dummy pivoted dataframe
@@ -0,0 +1,179 @@
1
+ # Copyright (C) 2026 Kian-Meng Ang
2
+ #
3
+ # This program is free software: you can redistribute it and/or modify
4
+ # it under the terms of the GNU Affero General Public License as published
5
+ # by the Free Software Foundation, either version 3 of the License, or
6
+ # (at your option) any later version.
7
+ #
8
+ # This program is distributed in the hope that it will be useful,
9
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
10
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
+ # GNU Affero General Public License for more details.
12
+ #
13
+ # You should have received a copy of the GNU Affero General Public License
14
+ # along with this program. If not, see <https://www.gnu.org/licenses/>.
15
+
16
+ import pandas as pd
17
+ from matplotlib.axes import Axes
18
+ from matplotlib.offsetbox import AnnotationBbox, TextArea
19
+
20
+ from heatmap_cli.cli import _process_args, build_parser
21
+ from heatmap_cli.heatmap import (
22
+ GRADE_LEGEND_ENTRIES,
23
+ GRADE_LEGEND_LABEL,
24
+ _setup_plot_artists,
25
+ )
26
+
27
+ GRADE_DATA = [[120, 80, 60, 30], [10, 5, 0, 0]]
28
+
29
+ GENERATED_BY = "Generated by: pypi.org/project/heatmap_cli, colormap: vlag"
30
+
31
+ GENERATED_BY_COUNT = f"{GENERATED_BY}, count: nearest hundred"
32
+
33
+
34
+ def _expected_legend_line() -> str:
35
+ line = GRADE_LEGEND_LABEL
36
+ for index, (grade, label, _value) in enumerate(GRADE_LEGEND_ENTRIES):
37
+ gap = " " if index == 0 else " "
38
+ line += f"{gap}{grade} {label}"
39
+ return line
40
+
41
+
42
+ def _collect_text_areas(artist) -> list[TextArea]:
43
+ areas = [artist] if isinstance(artist, TextArea) else []
44
+ for child in artist.get_children():
45
+ areas.extend(_collect_text_areas(child))
46
+ return areas
47
+
48
+
49
+ def _legend_areas(axes: Axes) -> list[TextArea]:
50
+ boxes = [
51
+ artist for artist in axes.artists if isinstance(artist, AnnotationBbox)
52
+ ]
53
+ assert len(boxes) == 1
54
+ return _collect_text_areas(boxes[0].offsetbox)
55
+
56
+
57
+ def _assert_legend_rows(axes: Axes) -> list[TextArea]:
58
+ """Check the week, legend and Generated by rows and return the areas."""
59
+ areas = _legend_areas(axes)
60
+ texts = [area.get_text() for area in areas]
61
+ assert texts[0] == "week"
62
+ assert "".join(texts[1:-1]) == _expected_legend_line()
63
+ assert texts[-1] == GENERATED_BY
64
+ return areas
65
+
66
+
67
+ def _render(config):
68
+ dataframe = pd.DataFrame(
69
+ GRADE_DATA,
70
+ index=[1, 2],
71
+ columns=["01", "02", "03", "04"],
72
+ )
73
+ dataframe.index.name = "weekday"
74
+ dataframe.columns.name = "week"
75
+ return _setup_plot_artists("vlag", config, dataframe)
76
+
77
+
78
+ def test_heatmap_style_grade_annotations(csv_file):
79
+ """The grade style annotates each cell with a letter grade."""
80
+ csv = csv_file("sample.csv")
81
+ parser = build_parser()
82
+
83
+ assert parser.parse_args([str(csv)]).heatmap_style == "number"
84
+
85
+ parsed_args = parser.parse_args([str(csv), "--heatmap-style", "grade"])
86
+ config = _process_args(parser, parsed_args)
87
+
88
+ _fig, axis = _render(config)
89
+
90
+ assert [text.get_text() for text in axis.texts] == [
91
+ "X",
92
+ "A",
93
+ "B",
94
+ "C",
95
+ "D",
96
+ "E",
97
+ ".",
98
+ ".",
99
+ ]
100
+ assert axis.get_xlabel() == ""
101
+
102
+ _assert_legend_rows(axis)
103
+
104
+
105
+ def test_grade_legend_letters_use_heatmap_colors(csv_file):
106
+ """Each legend grade letter uses the color of its heatmap cells."""
107
+ csv = csv_file("sample.csv")
108
+ parser = build_parser()
109
+ parsed_args = parser.parse_args([str(csv), "--heatmap-style", "grade"])
110
+ config = _process_args(parser, parsed_args)
111
+
112
+ _fig, axis = _render(config)
113
+
114
+ mesh = axis.collections[0]
115
+ areas = _assert_legend_rows(axis)
116
+ assert areas[1].get_text() == GRADE_LEGEND_LABEL
117
+
118
+ colors = []
119
+ for index, (grade, label, value) in enumerate(GRADE_LEGEND_ENTRIES):
120
+ grade_area = areas[2 + 2 * index]
121
+ label_area = areas[3 + 2 * index]
122
+ assert grade_area.get_text().strip() == grade
123
+ assert label_area.get_text().strip() == label
124
+ color = grade_area.get_children()[0].get_color()
125
+ assert color == mesh.cmap(mesh.norm(value))
126
+ colors.append(color)
127
+ assert len(set(colors)) == len(GRADE_LEGEND_ENTRIES)
128
+
129
+
130
+ def test_heatmap_style_grade_ignores_colorbar(csv_file):
131
+ """The grade legend replaces the colorbar, so --cbar is ignored."""
132
+ csv = csv_file("sample.csv")
133
+ parser = build_parser()
134
+ parsed_args = parser.parse_args(
135
+ [str(csv), "--heatmap-style", "grade", "--cbar"],
136
+ )
137
+ config = _process_args(parser, parsed_args)
138
+
139
+ _fig, axis = _render(config)
140
+
141
+ assert axis.collections[0].colorbar is None
142
+
143
+ _assert_legend_rows(axis)
144
+
145
+
146
+ def test_heatmap_style_number_keeps_colorbar_without_legend(csv_file):
147
+ """The number style keeps the colorbar and draws no grade legend."""
148
+ csv = csv_file("sample.csv")
149
+ parser = build_parser()
150
+ parsed_args = parser.parse_args(
151
+ [str(csv), "--heatmap-style", "number", "--cbar"],
152
+ )
153
+ config = _process_args(parser, parsed_args)
154
+
155
+ _fig, axis = _render(config)
156
+
157
+ cbar = axis.collections[0].colorbar
158
+ assert cbar is not None
159
+ assert cbar.ax.get_xlabel() == GENERATED_BY_COUNT
160
+ assert not [
161
+ artist for artist in axis.artists if isinstance(artist, AnnotationBbox)
162
+ ]
163
+
164
+
165
+ def test_heatmap_style_grade_warns_cbar_ignored(cli_runner, csv_file):
166
+ """--cbar with the grade style must warn that it has no effect."""
167
+ csv = csv_file("sample.csv")
168
+ ret = cli_runner(
169
+ csv,
170
+ "--heatmap-style",
171
+ "grade",
172
+ "--cbar",
173
+ "-y",
174
+ "2023",
175
+ expect_error=False,
176
+ )
177
+ assert "argument --cbar: ignored with --heatmap-style grade" in (
178
+ ret.stderr
179
+ )
@@ -44,6 +44,7 @@ def test_setup_plot_artists_no_annotate(tmpdir):
44
44
  output_dir=str(tmpdir),
45
45
  format="png",
46
46
  open=False,
47
+ heatmap_style="number",
47
48
  )
48
49
 
49
50
  df = pd.DataFrame([[10, 20], [30, 40]], index=[1, 2], columns=["01", "02"])
@@ -63,6 +64,7 @@ def test_configure_heatmap_options_no_annotate():
63
64
  cbar=True,
64
65
  cmap_min=None,
65
66
  cmap_max=None,
67
+ heatmap_style="number",
66
68
  )
67
69
 
68
70
  options = _configure_heatmap_options(config, "vlag", axis)
File without changes
File without changes