class_docstr: This object provides the primary interface to the functionality of this library. You can think of it as
  an adaptor that adapts the various decision-tree based libraries for use with dtreeviz. In implementation,
  however, this object encapsulates the key functionality and API but delegates tree model adaptation
  from sklearn etc... to dtreeviz.models.ShadowDecTree subclasses.
class_docstr_tok: ["This","object","provides","the","primary","interface","to","the","functionality","of","this","library",".","You","can","think","of","it","as","an","adaptor","that","adapts","the","various","decision-tree","based","libraries","for","use","with","dtreeviz",".","In","implementation",",","however",",","this","object","encapsulates","the","key","functionality","and","API","but","delegates","tree","model","adaptation","from","sklearn","etc","...","to","dtreeviz.models.ShadowDecTree","subclasses","."]
docstr: Visualize the distribution of classes for each leaf.
  
  It's a good way to see how classes are distributed in leaves. For example, you can observe that in some
  leaves all the samples belong only to one class, or that in other leaves the distribution of classes is almost
  50/50.
  You could get all the samples from these leaves (using node_stats() function) and look over/understand what they have in common.
  Now, you can understand your data in a model driven way.
  
  Usage example :
  viz_model = dtreeviz.model(tree_model, X_train=dataset[features], y_train=dataset[target],
                             feature_names=features, target_name=target, class_names=[0, 1])
  viz_model.ctree_leaf_distributions()
  
  :param display_type: str, optional
     'plot' or 'text'
  :param xaxis_display_type: str, optional
     'individual': Displays every node ID individually
     'auto': Let matplotlib automatically manage the node ID ticks
     'y_sorted': Display in y order with no x-axis tick labels
  :param show_leaf_id_list: list, optional
     The allowed list of node id values to plot
  :param show_leaf_filter: Callable[[np.ndarray], bool], optional
     The filtering function to apply to leaf values before displaying the leaves.
     The function is applied to a numpy array with the class i sample value in row i.
     For example, to view only those leaves with more than 100 total samples, and more than 5 class 1 samples, use show_leaf_filter = lambda x: (100 < np.sum(x)) & (5 < x[1])
  :param plot_ylim: int, optional
      The max value for oY. This is useful in case we have few leaves with big sample values which 'shadow'
      the other leaves values.
  :param colors: dict
      The set of colors used for plotting
  :param fontsize: int
      Plot labels fontsize
  :param fontname: str
      Plot labels font name
  :param grid: bool
      True if we want to display the grid lines on the visualization
  :param figsize: optional (width, height) in inches for the entire plot
      :param ax: optional matplotlib "axes" to draw into
code: def ctree_leaf_distributions(
      self,
      display_type: ("plot", "text") = "plot",
      xaxis_display_type: str = "individual",
      show_leaf_id_list: list = None,
      show_leaf_filter: Callable[[np.ndarray], bool] = None,
      plot_ylim: int = None,
      colors: dict = None,
      fontsize: int = 10,
      fontname: str = "Arial",
      grid: bool = False,
      figsize: tuple = None,
      ax=None,
  ):
      """Visualize the distribution of classes for each leaf.
  
      It's a good way to see how classes are distributed in leaves. For example, you can observe that in some
      leaves all the samples belong only to one class, or that in other leaves the distribution of classes is almost
      50/50.
      You could get all the samples from these leaves (using node_stats() function) and look over/understand what they have in common.
      Now, you can understand your data in a model driven way.
  
      Usage example :
      viz_model = dtreeviz.model(tree_model, X_train=dataset[features], y_train=dataset[target],
                                 feature_names=features, target_name=target, class_names=[0, 1])
      viz_model.ctree_leaf_distributions()
  
      :param display_type: str, optional
         'plot' or 'text'
      :param xaxis_display_type: str, optional
         'individual': Displays every node ID individually
         'auto': Let matplotlib automatically manage the node ID ticks
         'y_sorted': Display in y order with no x-axis tick labels
      :param show_leaf_id_list: list, optional
         The allowed list of node id values to plot
      :param show_leaf_filter: Callable[[np.ndarray], bool], optional
         The filtering function to apply to leaf values before displaying the leaves.
         The function is applied to a numpy array with the class i sample value in row i.
         For example, to view only those leaves with more than 100 total samples, and more than 5 class 1 samples, use show_leaf_filter = lambda x: (100 < np.sum(x)) & (5 < x[1])
      :param plot_ylim: int, optional
          The max value for oY. This is useful in case we have few leaves with big sample values which 'shadow'
          the other leaves values.
      :param colors: dict
          The set of colors used for plotting
      :param fontsize: int
          Plot labels fontsize
      :param fontname: str
          Plot labels font name
      :param grid: bool
          True if we want to display the grid lines on the visualization
      :param figsize: optional (width, height) in inches for the entire plot
          :param ax: optional matplotlib "axes" to draw into
      """
      (
          index,
          leaf_samples,
      ) = self.shadow_tree.get_leaf_sample_counts_by_class()
      if display_type == "plot":
          colors = adjust_colors(colors)
          colors_classes = colors["classes"][
              self.shadow_tree.nclasses()
          ]
  
          if ax is None:
              if figsize:
                  fig, ax = plt.subplots(figsize=figsize)
              else:
                  fig, ax = plt.subplots()
  
          leaf_samples_hist = [
              [] for i in range(self.shadow_tree.nclasses())
          ]
          for leaf_sample in leaf_samples:
              for i, leaf_count in enumerate(leaf_sample):
                  leaf_samples_hist[i].append(leaf_count)
          leaf_samples_hist = np.array(leaf_samples_hist)
  
          if show_leaf_id_list is not None:
              _mask = np.isin(index, show_leaf_id_list)
              leaf_samples_hist = leaf_samples_hist[:, _mask]
              index = tuple(np.array(index)[_mask])
          if show_leaf_filter is not None:
              _mask = np.apply_along_axis(
                  show_leaf_filter, 0, leaf_samples_hist
              )
              leaf_samples_hist = leaf_samples_hist[:, _mask]
              index = tuple(np.array(index)[_mask])
  
          if xaxis_display_type == "individual":
              x = np.arange(0, len(index))
              ax.set_xticks(x)
              ax.set_xticklabels(index)
          elif xaxis_display_type == "auto":
              x = np.array(index)
              ax.set_xlim(np.min(x) - 1, np.max(x) + 1)
          elif xaxis_display_type == "y_sorted":
              # sort by total y = sum(classes), then class 0, 1, 2, ...
              sort_cols = [np.sum(leaf_samples_hist, axis=0)]
              for i in range(leaf_samples_hist.shape[0]):
                  sort_cols.append(leaf_samples_hist[i])
              _sort = np.lexsort(sort_cols[::-1])[::-1]
              leaf_samples_hist = leaf_samples_hist[:, _sort]
              index = tuple(np.array(index)[_sort])
  
              x = np.arange(0, len(index))
              ax.set_xticks(x)
              ax.set_xticklabels([])
              ax.tick_params(axis="x", which="both", bottom=False)
          else:
              raise ValueError(
                  f"Unknown xaxis_display_type = {xaxis_display_type}!"
              )
  
          if plot_ylim is not None:
              ax.set_ylim(0, plot_ylim)
  
          bottom_values = np.zeros(len(index))
          for i in range(leaf_samples_hist.shape[0]):
              bar_container = ax.bar(
                  x,
                  leaf_samples_hist[i],
                  bottom=bottom_values,
                  color=colors_classes[i],
                  lw=0.3,
                  align="center",
                  width=1,
              )
              bottom_values = bottom_values + leaf_samples_hist[i]
  
              for rect in bar_container.patches:
                  rect.set_linewidth(0.5)
                  rect.set_edgecolor(colors["rect_edge"])
  
          class_values = self.shadow_tree.classes()
          n_classes = self.shadow_tree.nclasses()
          color_values = colors["classes"][n_classes]
          color_map = {
              v: color_values[i] for i, v in enumerate(class_values)
          }
          add_classifier_legend(
              ax,
              self.shadow_tree.class_names,
              class_values,
              color_map,
              self.shadow_tree.target_name,
              colors,
              fontname=fontname,
          )
  
          _format_axes(
              ax,
              "Leaf IDs",
              "Samples by Class",
              colors,
              fontsize,
              fontname,
              ticks_fontsize=None,
              grid=grid,
          )
  
      elif display_type == "text":
          for i, leaf in enumerate(index):
              print(f"leaf {leaf}, samples : {leaf_samples[i]}")
  
imports: import os
  import tempfile
  from typing import Mapping, List, Callable
  import matplotlib
  import matplotlib.patches
  import matplotlib.pyplot
  import numpy
  import pandas
  from colour import Color, rgb2hex
  from sklearn import tree
  from dtreeviz.colors import adjust_colors
  from dtreeviz.interpretation import explain_prediction_plain_english, explain_prediction_sklearn_default
  from dtreeviz.models.shadow_decision_tree import ShadowDecTree
  from dtreeviz.models.shadow_decision_tree import ShadowDecTreeNode
  from dtreeviz.utils import myround, DTreeVizRender, add_classifier_legend, _format_axes, _draw_wedge, _set_wedge_ticks, tessellate, is_numeric
label_desc: Use image node_id 3 for calling the DTreeVizAPI obj's underlying member method code with example usage: obj.ctree_leaf_distributions(display_type, xaxis_display_type, show_leaf_id_list, show_leaf_filter, plot_ylim, colors, fontsize, fontname, grid, figsize, ax) without return types